Dan*_*hin 5 scala higher-kinded-types type-projection
考虑以下:
trait Foo {
type F[_]
type A
type FA = F[A]
def get: FA
}
class SeqStringFoo extends Foo {
type F[_] = Seq[_]
type A = String
def get: Seq[String] = Seq("hello world")
}
def exec[F <: Foo](foo: F): F#FA = foo.get
val seq1: Seq[Any] = exec(new SeqStringFoo()) // Seq[Any] = List(hello world)
val seq2: Seq[String] = exec(new SeqStringFoo()) // Error: Expression SeqIntFoo#FA doesn't conform to Seq[String]
Run Code Online (Sandbox Code Playgroud)
seq2因为某些原因,String在使用类型投影 时,包装类型的类型信息会丢失F#FA.
当返回的类型不是更高级的类型时,这不会发生.
为什么会这样?
我该如何解决这个问题?
看起来你在专业化中忘了F [_]的传递类型变量,试试:
class SeqStringFoo extends Foo {
type F[x] = Seq[x]
type A = String
def get: FA = Seq("hello world")
}
Run Code Online (Sandbox Code Playgroud)
在其他情况下,你总是返回Seq[_](== Seq[Any])任何F[_](F[Int],F[String])
| 归档时间: |
|
| 查看次数: |
110 次 |
| 最近记录: |