[英]scala override trait with generic method
I have 3 classes: 我有3节课:
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 ??? 我知道有一种方法可以使用类参数:trait Converter [T <:Base],并且还看到了这篇文章https://stackoverflow.com/a/4627144/980275我在问是否有解决方案而不更改特质??? Thank you
谢谢
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. 您必须参数化
Converter
特质或使用其他方法名称。
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: 但是,您可以接收
Base
对象并将其强制转换,但是不建议您这样做,因为它可能会在运行时导致异常:
object ConverterBaseOne extends Converter {
override def toAClass[T <: Base](e: T): AClass = {
printf(e.asInstanceOf[BaseOne].b)
// ...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.