Y4s*_*per 3 generics scala case-class
我目前正在研究Scala中的A*实现.为了实现一个干净的结构,我想使用一个嵌套的case类结构,它实现了一个自我限制的特征.但是,在Scala IDE中实现它时遇到了一些问题.以下代码将无法编译:
trait A[T <: A[T]]
class B {
case class C(int: Int) extends A[C] // A[this.C] won't work either
def make = C(5)
}
object D {
def foo[T <: A[T]](some: T) = {}
val c = new B().make
foo(c) // this does not compile
}
Run Code Online (Sandbox Code Playgroud)
有什么方法可以使这个结构有效吗?
不知道为什么你想要这个,但这就是为什么它不会按原样运作:
类型D.c是B#C.它是一种路径依赖类型,我们不知道B它属于哪个实例.但是,Cextends A[C],就像A[this.C]在该上下文中所说的那样,它被绑定到特定的实例B.foo将type参数T视为B#C,与b.C某些参数不同b.
您有两个选项可以进行编译.
放松的约束A来B#C:
trait A[T <: A[T]]
class B {
case class C(int: Int) extends A[B#C]
def make = C(5)
}
object D {
def foo[T <: A[T]](some: A[T]) = {}
val c = new B().make
foo(c)
}
Run Code Online (Sandbox Code Playgroud)
或者处理路径依赖类型,以便c具有类型b.C:
trait A[T <: A[T]]
class B {
case class C(int: Int) extends A[C]
def make = C(5)
}
object D {
def foo[T <: A[T]](some: A[T]) = {}
val b = new B
val c: b.C = b.make
foo(c)
}
Run Code Online (Sandbox Code Playgroud)