0

I am trying to return a subclass of an abstract generic class in Scala but it won't compile. I get Expression of type A doesn't conform to to expected type B. here is the code I am using:

abstract class AA[T](val var1: String){
  def doSomething(): T;
}
class BB(override val var1: String) extends AA[Int](var1){
  override def doSomething(): Int = {
    return 5
  }
}

object Factory {
  def create(v: String) : AA[Any] = {
  return new BB("5") // this is the error
  }
}

What should be the signature of create()?

Thanks

Ulile
  • 251
  • 1
  • 3
  • 9

1 Answers1

1

BB extends AA[Int] but Factory.create claims to return an AA[Any]. You can fix this by making AA covariant in T:

abstract class AA[+T](val var1: String){
  def doSomething(): T
}
Seth Tisue
  • 29,985
  • 11
  • 82
  • 149
Lee
  • 142,018
  • 20
  • 234
  • 287