scala override trait with generic method

2019-08-11 16:40发布

问题:

I have 3 classes:

class AClass 
class Base { val a = "a" }
class BaseOne extends Base { val b = "b" }
class BaseTwo extends Base { val c = "c" }

I want to extend a trait which contains a generic method, I'm not allowed to change the trait

trait Converter {
    def toAClass[T <: Base](e: T): AClass
    def fromAClass[T <: Base](s: AClass): T
}

I want to extend it in several different objects

 object ConverterBaseOne extends Converter { 
 // ERROR
     override def toAClass(e: BaseOne) : AClass = { printf(e.b) } // b is known
     override def fromAlcass(a: AClass) : BaseTwo = {....}
 }

I know there is a way to do it with class parameter: trait Converter[T <: Base] and also saw this post https://stackoverflow.com/a/4627144/980275 I'm asking if there is a solution without changing the trait ??? Thank you

回答1:

You are changing the signature of the method, so it is not a legal override, it would break polymorphism. You must either parametrize the Converter trait or use another method name.

You can, however, receive a Base object and cast it, but it is not recommended practice since it may result in an exception at runtime:

object ConverterBaseOne extends Converter { 
  override def toAClass[T <: Base](e: T): AClass = {
    printf(e.asInstanceOf[BaseOne].b)
    // ...
  }
}