par*_*tic 12 types scala type-inference
当我尝试编译小例子时:
trait Foo[A,B] {
type F[_,_]
def foo(): F[A,B]
}
class Bar[A,B] extends Foo[A,B] {
type F[D,E] = Bar[D,E]
def foo() = this
}
object Helper {
def callFoo[A,B,FF <: Foo[A,B]]( f: FF ): FF#F[A,B] =
f.foo()
}
object Run extends App {
val x = new Bar[Int,Double]
val y = Helper.callFoo(x)
println( y.getClass )
}
Run Code Online (Sandbox Code Playgroud)
我收到错误:
[error] src/Issue.scala:20: inferred type arguments
[Nothing,Nothing,issue.Bar[Int,Double]] do not conform to method callFoo's type
parameter bounds [A,B,FF <: issue.Foo[A,B]]
[error] val y = Helper.callFoo(x)
Run Code Online (Sandbox Code Playgroud)
显然,类型推断机制无法推断Bar [A,B]中的A和B. 但是,如果我手动传递所有类型,它会起作用:
val y = Helper.callFoo[Int,Double,Bar[Int,Double]](x)
Run Code Online (Sandbox Code Playgroud)
我有办法避免明确传递类型吗?
Jea*_*let 11
您必须将签名更改为callFoo:
def callFoo[A, B, FF[A, B] <: Foo[A, B]](f: FF[A, B]): FF[A, B]#F[A, B] =
Run Code Online (Sandbox Code Playgroud)
您必须告诉编译器FF实际上是参数化类型.