我刚开始学习 Scala,来自 Java 背景。我一直在尝试理解函数中的类型参数和类型的推断。这是 Scala 文档中的标准示例:
class Decorator(left: String, right: String) {
def layout[A](x: A) = left + x.toString() + right
}
object FunTest extends Application {
def apply(f: Int => String, v: Int) = f(v)
val decorator = new Decorator("[", "]")
println(apply(decorator.layout, 7))
}
如果我尝试将类型参数应用于apply
函数并保持v
强类型,则会发生类型不匹配。为什么这里没有推断出类型?
def apply[B](f: B => String, v: String) = f(v) //Type mismatch
def apply[B](f: B => String, v: B) = f(v) //Works fine
谢谢