我最近碰到這個例子跑,它打印「[7]」使用參數化類型參數聲明一個方法的優點與聲明參數爲Any?
class Decorator(left: String, right: String) {
def layout[A](x: A) = left + x.toString() + right
}
def apply(f: Int => String, v: Int) = f(v)
val decorator = new Decorator("[", "]")
println(apply(decorator.layout, 7))
這也有可能宣佈Decorator
這樣的:
class Decorator(left: String, right: String) {
def layout(x: Any) = left + x.toString() + right
}
我很好奇,想知道是什麼第一種方法的優點?