Scala Newbie

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?

+3
source share
2 answers

Your signature indicates that there is a parameterless method foo that returns a function from Int to Int. You have a method with the parameter Int and Int Result.

Do you want to

duck: {def foo(i: Int) : Int}

( )

+7

, "duckTyped", "foo", Int = > Int .

, . , :

a "foo", Int = > Int.

"" Int => Int, (.. ), .

, .

, .

, , :

def f(x: Int): Int = x * 2
def f: Int => Int = x => x * 2

Int, Int => Int. Int, .

+4

All Articles