I think about Scala again and hope that this will be the main question regarding duck text input, or maybe it really is 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 called “duckTyped” that will accept any object if that object has a method called “foo” which is an Int => Int function.
Why does the declaration of the function foo in the class "DoublerThatWontWork" not satisfy the parameter type of the duckTyped function?
source
share