[英]Inference of type parameters on mixins
Let's say I have some trait: 比方说我有一些特点:
trait A[T] { def foo: T }
A class which extends it: 扩展它的类:
class B[T](t: T) extends A[T] { def foo = t }
And a subtrait of the parent trait: 父母特质的一个子特征:
trait C[T] extends A[T]
I want to mix C in with B. 我想把C和B混在一起。
val foo = new B("foo") with C[String]
This works fine, but I'd rather not need to specify the type parameter again, since B is already of type A[String]. 这样可以正常工作,但我不需要再次指定类型参数,因为B已经是A [String]类型。 However, I recognize Scala doesn't support the following: 但是,我认为Scala不支持以下内容:
val foo = new B("foo") with C
My question is where there's some other mechanism in the type system to support not having to specify the type parameters when C is mixed in. What I was thinking of was something as follows: 我的问题是类型系统中有一些其他机制支持在混合C时不必指定类型参数。我想到的是如下内容:
trait C {
self: A[T] => ...
}
One would think this kind of thing would fix what C could be mixed into. 人们会认为这种事情可以解决C可能混入的问题。 However, it isn't valid Scala. 但是,Scala无效。 Something like: 就像是:
trait C {
type T
self: A[T] =>
}
does not work either. 也不起作用。
How about this: 这个怎么样:
scala> trait C {
| self: A[_] =>
| }
defined trait C
scala> val foo = new B("foo") with C
foo: B[String] with C = $anon$1@f2df380
scala> foo.foo
res16: String = foo
You can do this using an abstract type: 您可以使用抽象类型执行此操作:
trait A {
type AT
def foo: AT
}
class B[T](t: T) extends A {
type AT = T
def foo = t
}
trait C extends A
val foo = new B("foo") with C
The definition is a bit more verbose, but your requirement of not having to type T
again is satisfied. 定义有点冗长,但是您不必再次输入T
要求就满足了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.