2
编译此代码类型别名和多个参数列表功能类型推断
case class MyType()
object TestMe extends App {
type Fun[T] = T => Int
def myFun[T](x: T): Int = ???
def matcher[T](f: Fun[T])(p: T): Int = ???
var f = myFun[MyType] _
val p = MyType()
matcher(f)(p)
}
失败,此错误:
Error:(16, 11) type mismatch;
found : ... MyType => Int
required: ... TestMe.Fun[T]
(which expands to) T => Int
matcher(f)(p)
更改为如下所示的代码可以解决问题:
case class MyType()
object TestMe extends App {
type Fun[T] = T => Int
def myFun[T](x: T): Int = ???
def matcher[T](f: Fun[T])(p: T): Int = ???
var f: Fun[MyType] = myFun[MyType] // <-- Explicit type
val p = MyType()
matcher(f)(p)
}
另外更改参数顺序可修复问题:
case class MyType()
object TestMe extends App {
type Fun[T] = T => Int
def myFun[T](x: T): Int = ???
def matcher[T](p: T)(f: Fun[T]): Int = ??? // <-- Flipping the argument, so the first argument have explicitly the parametric type
var f = myFun[MyType] _
val p = MyType()
matcher(p)(f) // <-- Calls with flipped arguments
}
我的理解(我猜是因为我缺乏Scala知识)是'type'只是创建类型别名,但看起来不像那样。 有人可以解释编译失败的原因吗?
感谢