【问题标题】:Value is not a member of type parameter值不是类型参数的成员
【发布时间】:2023-03-17 08:59:01
【问题描述】:

我试图在隐式实现方法中调用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
    }
}

提前致谢

【问题讨论】:

  • [Dog] 只是一个随机类型参数。它可以是任何东西。删除它,这样你就不会隐藏案例类Dog
  • 你还通过定义另一个类型参数A给方法来隐藏Speakable的类型参数Aspeak中。

标签: scala generics typeclass


【解决方案1】:

你的类型类不需要额外的类型参数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你没有使用你的类Dog,你定义了隐藏类的新类型)。

【讨论】:

    猜你喜欢
    • 2013-05-05
    • 1970-01-01
    • 2013-05-06
    • 2015-05-01
    • 2019-07-11
    • 1970-01-01
    • 2019-02-03
    • 1970-01-01
    • 2013-04-06
    相关资源
    最近更新 更多