Scala Duck Typing Newbie
scala
Solution
Your signature says there is a method foo with no parameters, which returns a function from Int to Int. What you have is a method with an Int parameter and an Int Result.
you want
duck: {def foo(i: Int) : Int}
(parameter name does not have to match)
Problem
I'm poking around with Scala again and have what I hope will be a basic question regarding duck typing, or maybe it is really with function definitions. Let me explain: Given the following code: ``` 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 } ``` So basically I have a method "duckTyped" that will accept ANY object as long as that object has a method named "foo" that is a Int=>Int function. Why does the function declaration of foo in the class "DoublerThatWontWork" not satisfy the parameter type of function duckTyped?