私は再び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
}
したがって、基本的には、オブジェクトにInt=>Int関数である「foo」という名前のメソッドがある限り任意のオブジェクトを受け入れるメソッド「duckTyped」があります。
クラス「DoublerThatWontWork」のfooの関数宣言が、関数duckTypedのパラメーター型を満たさないのはなぜですか。