我想要一个可以在某些特征中混合的通用基类。
是否有可能让mixins自动采用基类的泛型?
abstract class Base[T] {
def foo: T = ???
def bar(value: T): Boolean
}
trait MixinA {
self: Base[U] => // U should be automatically bound to T of Base[T]
def bar(value: U): Boolean = false
}
您可以使用以下抽象类型来实现一些解决此问题的方法Base
:
abstract class Base[T] {
type U <: T
def foo: U = ???
def bar(value: U): Boolean
}
trait MixinA {
self: Base[_] =>
final def bar(value: U): Boolean = false
}
REPL测试:
scala> class Impl extends Base[Int] with MixinA
defined class Impl
scala> val i = new Impl
i: Impl = Impl@7ca5cc9e
scala> val x: Int = i.foo
scala.NotImplementedError: an implementation is missing
at scala.Predef$.$qmark$qmark$qmark(Predef.scala:225)
at Base.foo(<console>:9)
... 33 elided
如您所见,编译器正确地确定了它i.foo
是Int
(确实是 Int
)的子类型,因此可以分配给它x
(这里的例外是因为您未执行其主体)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句