[英]Value is not a member of type parameter
我试图在隐式实现方法中调用Dog
的方法bark
,但是我得到了
def speak[Dog](dog: Dog): String = dog.bark ^ 第 16 行:错误:值 bark 不是类型参数 Dog 的成员
这是我的代码
// Define class/type
case class Dog(val breed: String) {
val bark: String = s"Bark!! I am a $breed"
}
// Define interface
trait Speakable[A] {
def speak[A](animal: A): String
}
// Define interface companion object, where we can provide
// implicit implementation methods
object Speakable {
def speak[A](animal: A)(implicit sp: Speakable[A]) = sp.speak(animal)
implicit val dogSpeak: Speakable[Dog] = new Speakable[Dog] {
def speak[Dog](dog: Dog): String = dog.bark
}
}
提前致谢
您的类型 class 不需要额外的类型参数A
trait Speakable[A] {
def speak(animal: A): String
}
(当您定义方法的此类类型参数A
时,它隐藏了特征的类型参数A
)。
然后实例
implicit val dogSpeak: Speakable[Dog] = new Speakable[Dog] {
def speak(dog: Dog): String = dog.bark
}
也不需要方法的类型参数(当您定义此类类型参数Dog
您没有使用您的 class Dog
时,您定义了隐藏类的新类型)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.