Search code examples
scalainheritancetype-parameter

Getting error on calling method of a class type in parameterized class


The following exception is being thrown: InheritanceTest.sc:15: error: value bark is not a member of type parameter T k9.bark

The code is :

class Dog {
    def bark: Unit = {
        println("bhow bhow!")
    }
}

class Puppy extends Dog {
    override def bark: Unit = {
        println("woof woof!")
    }
}

class Animal[+T](val k9: T) {
    def voice: Unit = {
       k9.bark
    }
}

object InheritanceTest{
  def main(args: Array[String]): Unit = {
    val puppy = new Puppy
    val dog = new Dog

    val k91 = new Animal[Dog](dog)
    val k92 = new Animal[Puppy](puppy)

    k91.voice
    k92.voice

    println("Done.")
  }
}

Could Scala experts provide a solution or explain what is wrong in the code? Thanks for the help in advance.


Solution

  • You need to constrain type parameter T with upper type bound Dog like so

    T <: Dog
    

    otherwise the compiler thinks T represents all types, and not all types have bark on them. Thus try

    class Animal[+T <: Dog](val k9: T) {
      def voice: Unit = {
        k9.bark
      }
    }