I'm new to Scala and I try to understand how generic abstract classes/methods are working
The code below does not compile, from the error message it seems that the parameters of the methods overriding the abstracts are not of the type give as parameter to the class
abstract class Pet(someString: String) {
def name: String
}
class Cat(someString: String) extends Pet(someString) {
val name = someString;
}
class Dog(someString: String) extends Pet(someString) {
val name = someString;
}
abstract class Printer[+A] {
def print[B >: A](printableObject: B): Unit
}
class CatPrinter extends Printer[Cat] {
override def print[B >: Cat](cat: B): Unit = println("the cat name is: " + cat.name)
}
class DogPrinter extends Printer[Dog] {
override def print[B >: Dog](dog: B): Unit = println("the dog name is: " + dog.name)
}
object Test {
val myCat: Cat = new Cat("Booster")
def printMyCat(printer: Printer[Pet]): Unit = {
printer.print(myCat)
}
def main(args: Array[String]): Unit = {
val catPrinter = new CatPrinter
val dogPrinter = new DogPrinter
printMyCat(catPrinter)
printMyCat(dogPrinter)
}
}
The compilation fails with the below message
ScalaFiddle.scala:20: error: value name is not a member of type parameter B&0
override def print[B >: Cat](cat: B): Unit = println("the dog name is: " + cat.name)
^
ScalaFiddle.scala:24: error: value name is not a member of type parameter B&0
override def print[B >: Dog](dog: B): Unit = println("the dog name is: " + dog.name)
Any thoughts on why is the code not compiling and how I could make it work?