【发布时间】:2013-10-19 11:04:52
【问题描述】:
假设我有一个像这样的泛型类型:
class GenericEchoer[T <: Any] {
var content: T = _
def echo: String = "Echo: " + content.toString
}
然后可以创建一个 mixin,允许像这样扩展 GenericEchoer[T] 的功能:
trait Substitution[T <: AnyRef] extends GenericEchoer[T] {
def substitute(newValue: T) = { content = newValue }
}
定义了这些,我可以用这种方式实例化类型:
val echoer = new GenericEchoer[Int] with Substitution[Int]
我的问题是:如何实现类似的功能,以便我可以在 mixin 中省略类型参数?换句话说,我希望能够使用以下行实例化相同的类型:
val echoer = new GenericEchoer[Int] with Substitution
但是,这不起作用,因为 Substitution“不知道”基础类型参数。
【问题讨论】:
-
如果
Substitution扩展GenericEchoer然后Susbstitution with GenericEchoer扩展GenericEchoer两次。你可能想解决这个问题。另外你为什么要限制T <: AnyRef类型然后尝试使用Int这绝对不是AnyRef