【发布时间】:2017-04-26 13:12:42
【问题描述】:
编译这段代码
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 知识)是“类型”只是创建类型别名,但看起来不像那样。 有人可以解释编译失败的原因吗?
谢谢
【问题讨论】:
标签: scala