斯卡拉鸭子打字新手

joh*_*ase 3 scala

我再次与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
}
Run Code Online (Sandbox Code Playgroud)

所以基本上我有一个接受任何对象的方法"duckTyped",只要该对象有一个名为"foo"的方法,它是一个Int => Int函数.

为什么类"DoublerThatWontWork"中foo的函数声明不满足函数duckTyped的参数类型?

Did*_*ont 7

你的签名说有一个没有参数的方法foo,它返回一个从Int到Int的函数.你拥有的是一个带有Int参数和Int Result的方法.

你要

duck: {def foo(i: Int) : Int}
Run Code Online (Sandbox Code Playgroud)

(参数名称不必匹配)