简体   繁体   中英

Value is not a member of type parameter

I am trying to call method bark of Dog in an implicit implementation method, however I am getting

def speak[Dog](dog: Dog): String = dog.bark ^ On line 16: error: value bark is not a member of type parameter Dog

Here is my code

// 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
    }
}

Thanks in advance

Your type class doesn't need extra type parameter A

trait Speakable[A] {
  def speak(animal: A): String
}

(when you defined such type parameter A of the method it hid the type parameter A of the trait).

And then the instance

implicit val dogSpeak: Speakable[Dog] = new Speakable[Dog] {
  def speak(dog: Dog): String = dog.bark
}

also doesn't need type parameter of the method (when you defined such type parameter Dog you didn't use your class Dog , you defined new type hiding the class).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM