gpt4 book ai didi

Scala Duck 打字新手

转载 作者:行者123 更新时间:2023-12-01 08:15:58 27 4
gpt4 key购买 nike

我又在 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
}

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

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

最佳答案

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

你要

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

(参数名称不必匹配)

关于Scala Duck 打字新手,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10355296/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com