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'只是創建類型別名,但看起來不像那樣。 有人可以解釋編譯失敗的原因嗎?
感謝