我拼凑了这个问题的答案:Scala mixin to class instance ,在那里我展示了一种将另一个特征或类实例“混合”到现有实例的方法:
case class Person(name: String)
val dave = Person("Dave")
val joe = Person("Joe")
trait Dog { val dogName: String }
val spot = new Dog { val dogName = "Spot" }
implicit def daveHasDog(p: dave.type) = spot
dave.dogName //"Spot"
joe.dogName //error: value dogName is not a member of Person
所以在局部隐式定义之后,
dave
可以有效地用作 Person with Dog
.我的问题是,如果我们想定义一个接受 Person
的方法仅实例所在的 Person
有一个 Dog
, 我们该怎么做呢?我可以定义一个方法,例如
def showDog(pd: Person with Dog) = pd.name + " shows " + pd.dogName
然而这对
dave
没有好处因为他还只是一个Person
,尽管他有隐性的变身能力。我试着定义
trait Dog [T] { val dogName: String }
val spot = new Dog [dave.type] { val dogName = "Spot" }
def showDog(p: Person)(implicit dog: Dog[p.type]) = ...
但这不合法,给
error: illegal dependent method type
.有任何想法吗?
最佳答案
如果你用 -Ydependent-method-types
编译,您的原始代码将适用于 showDog
的此定义:
scala> def showDog(p: Person)(implicit ev: p.type => Dog) = p.name + " shows " + p.dogName
showDog: (p: Person)(implicit ev: p.type => Dog)java.lang.String
scala> showDog(dave)
res1: java.lang.String = Dave shows Spot
关于scala - 我们可以使用单例 .type 作为类型参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10200203/