通用方法的scala覆盖特征 [英] scala override trait with generic method
问题描述
我有3个类:
class AClass
class Base {val a =a}
class BaseOne extends Base {val b =b}
class BaseTwo extends Base {val c =c}
我想扩展一个包含泛型方法的特性,我不允许改变特性 我想将它扩展到几个不同的对象中 我知道有一种方法可以通过类参数来实现:trait Converter [T< base] 您正在更改方法的签名,因此它不是合法的重写,它会打破多态性。您必须参数化 然而,您可以收到 I have 3 classes: I want to extend a trait which contains a generic method, I'm not allowed to change the trait I want to extend it in several different objects 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 You are changing the signature of the method, so it is not a legal override, it would break polymorphism. You must either parametrize the You can, however, receive a
这篇关于通用方法的scala覆盖特征的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
< pre $ $ $ $ $ $ def fromAClass [T< base](s: AClass):T
}
object ConverterBaseOne extends Converter {
//错误
覆盖def toAClass(e:BaseOne):AClass = {printf (eb)} // b已知
覆盖自fromAlcass(a:AClass)的def:BaseTwo = {....}
}
并且还看到了这个帖子https://stackoverflow.com/a/4627144/980275
我问是否有解决方案,而不改变特质?
谢谢
Converter
trait或使用另一个方法名称。
Base
对象并进行强制转换,但不建议练习,因为它可能会在运行时导致异常:
// ...
}
}
class AClass
class Base { val a = "a" }
class BaseOne extends Base { val b = "b" }
class BaseTwo extends Base { val c = "c" }
trait Converter {
def toAClass[T <: Base](e: T): AClass
def fromAClass[T <: Base](s: AClass): T
}
object ConverterBaseOne extends Converter {
// ERROR
override def toAClass(e: BaseOne) : AClass = { printf(e.b) } // b is known
override def fromAlcass(a: AClass) : BaseTwo = {....}
}
Converter
trait or use another method name.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)
// ...
}
}