我想給抽象類型賦予一個類的值給一個類,然後使用它的路徑依賴類型。請看下面的例子(使用斯卡拉2.10.1):Scala中的路徑依賴類內部類值
trait Foo {
type A
def makeA: A
def useA(a: A): Unit
}
object Test {
class IntFoo extends Foo {
type A = Int
def makeA = 1
def useA(a: Int) = println(a)
}
class FooWrap(val a: Foo) {
def wrapUse(v: a.A) = a.useA(v)
}
val foo = new IntFoo
/* Path dependent locally */
val bar = foo
bar.useA(foo.makeA) // works
/* Path dependent through class value */
val fooWrap = new FooWrap(foo)
fooWrap.a.useA(foo.makeA) // fails
// error: type mismatch; found : Int required: Test.fooWrap.a.A
fooWrap.wrapUse(foo.makeA) // fails
// error: type mismatch; found : Int required: Test.fooWrap.a.A
}
首先,我不明白,在本地和類值之間的情況下,爲什麼根本區別(注意是公共的,一成不變的值)的類型檢查失敗(因爲顯然Test.fooWrap.a.A =:= foo.A
)。這是Scala編譯器的限制嗎?
其次,我該如何實現我想要做的?
UPDATE
看來,這可以通過使用泛型和內嵌式的約束來實現:
class FooWrap[T](val a: Foo { type A = T }) {
def wrapUse(v: T) = a.useA(v)
}
然而,在我的情況,A
實際上是一個高kinded類型,所以該示例變爲:
trait Foo {
type A[T]
def makeA[T]: A[T]
def useA(a: A[_]): Unit
}
object Test {
class OptFoo extends Foo {
type A[T] = Option[T]
def makeA[T] = None
def useA(a: A[_]) = println(a.get)
}
class FooWrap(val a: Foo) {
def wrapUse(v: a.A[_]) = a.useA(v)
}
val foo = new OptFoo
/* Path dependent locally (snip) */
/* Path dependent through class value */
val fooWrap = new FooWrap(foo)
fooWrap.a.useA(foo.makeA) // fails
// polymorphic expression cannot be instantiated to expected type;
// found : [T]None.type required: Test.fooWrap.a.A[_]
fooWrap.wrapUse(foo.makeA) // fails
// polymorphic expression cannot be instantiated to expected type;
// found : [T]None.type required: Test.fooWrap.a.A[_]
}
http://stackoverflow.com/questions/14544269/scala-immutability-and-path-dependent的可能的複製型兼容性 – gzm0 2013-04-23 22:33:42