我再次使用 Scala 并有一个我希望是关于鸭子类型的基本问题,或者它可能真的与函数定义有关。让我解释:
给定以下代码:
package johnmcase.scala.oneoffs
object DuckTyping extends App {
def printIt(x:Int, y:Int) = println("Value with " + x + " = " + y);
// This method will accept ANY object that has a method named foo of type (Int) => Int
def duckTyped(duck: {def foo: (Int) => Int}) = {
List(1,2,3,4,5) foreach (i => printIt(i, duck.foo(i)))
}
println(new DoublerThatWontWork().foo(5))
println(new Doubler().foo(5))
println("DOUBLER:");
duckTyped(new Doubler());
println("Squarer:");
duckTyped(new Squarer());
println("AlwaysSeven:");
duckTyped(new AlwaysSeven());
println("DoublerThatWontWork :");
duckTyped(new DoublerThatWontWork ()); // COMPILER ERROR!!
}
class DoublerThatWontWork { // WHY??
def foo(x:Int) = x*2
}
class Doubler {
def foo = (x:Int) => x*2
}
class Squarer {
def foo = (x:Int) => x*x
}
class AlwaysSeven {
def foo = (x:Int) => 7
}
所以基本上我有一个方法“duckTyped”,只要该对象有一个名为“foo”的方法,它是一个 Int=>Int 函数,它就会接受任何对象。
为什么“DoublerThatWontWork”类中foo的函数声明不满足函数duckTyped的参数类型?