Tom*_*ell 8 scala scala-generics
所以这是scala 这个Java问题的一个相当直接的端口
我们有一堆特征采用通用参数,如下所示:
trait Ident { }
trait Container[I <: Ident] {
def foo(id: I): String
}
trait Entity[C <: Container[I], I <: Ident] {
def container: C
def foo(id: I) = container.foo(id)
}
Run Code Online (Sandbox Code Playgroud)
这有点工作,但它有点笨拙,因为我们必须在定义Entity的子类时提供Ident的类型和Container的类型.实际上,只有Container的类型就足够了类型信息:
class MyIdent extends Ident { }
class MyContainer extends Container[MyIdent] { }
class MyEntity extends Entity[MyContainer,MyIdent] { }
// ^^^^^^^ shouldn't really be necessary
Run Code Online (Sandbox Code Playgroud)
使用存在类型避免了实体需要采用两个参数......但是您当然不能在以后引用它.
trait Entity[C <: Container[I] forSome { type I <: Ident }] {
def container: C
def foo(id: I) = container.foo(id)
// ^^^ complains it has no idea what 'I' is here
}
Run Code Online (Sandbox Code Playgroud)
类似地将事物转换为使用成员类型也不起作用......
trait Ident { }
trait Container {
type I <: Ident
def foo(id: I): String
}
trait Entity {
type C <: Container
def container: C
def foo(id: C#I) = container.foo(id)
// ^^ type mismatch
}
Run Code Online (Sandbox Code Playgroud)
那么有人知道在Scala中是否有一个优雅的解决方案吗?
更新 给出这个答案我不确定这是否应该被视为一个错误
您已达到SI-4377;如果您提供显式类型归属,您将收到一个错误,我猜测该错误只是暴露了类型投影是使用存在性实现的:
trait Ident { }
trait Container {
type I <: Ident
def foo(id: I): String
}
trait Entity {
type C <: Container
def container: C
def foo(id: C#I): String = (container: C).foo(id: C#I)
// you will get something like: type mismatch;
// [error] found : Entity.this.C#I
// [error] required: _3.I where val _3: Entity.this.C
// as I said above, see https://issues.scala-lang.org/browse/SI-4377
}
Run Code Online (Sandbox Code Playgroud)
毫不夸张地说,这个(bug?)使使用类型成员的泛型编程成为一场噩梦。
不过有一个技巧,它将值转换为手工制作的自引用类型别名:
case object Container {
type is[C <: Container] = C with Container {
type I = C#I
// same for all other type members, if any
}
def is[C <: Container](c: C): is[C] = c.asInstanceOf[is[C]]
}
Run Code Online (Sandbox Code Playgroud)
现在使用它并Entity
编译:
trait Entity {
type C <: Container
def container: C
def foo(id: C#I): String = Container.is(container).foo(id)
// compiles!
}
Run Code Online (Sandbox Code Playgroud)
这当然是危险的,并且根据经验,只有当C
其所有类型成员在使用时都绑定到非抽象类型时,它才是安全的;请注意,情况并非总是如此,因为 Scala 允许您保留“未定义”类型成员:
case object funnyContainer extends Container {
// I'm forced to implement `foo`, but *not* the `C` type member
def foo(id: I): String = "hi scalac!"
}
Run Code Online (Sandbox Code Playgroud)