gpt4 book ai didi

带参数的 Scala 传递函数

转载 作者:行者123 更新时间:2023-12-01 18:18:38 24 4
gpt4 key购买 nike

将一个函数传递给另一个函数的 Scala 示例缺少传递函数 (timeFlies) 采用参数 (x) 的情况。

object Timer {
def oncePerSecond(callback: (Int) => Unit) {
while (true) { callback(x); Thread sleep 1000 }
}
def timeFlies(x: int) {
println("time flies like an arrow...")
}
def main(args: Array[String]) {
oncePerSecond(timeFlies(5))
}
}

如何让上面的代码工作?

编辑:我在每秒一次中添加了一个 x 以澄清目标是传递整数。

最佳答案

至少有两种方法可以做到这一点,具体取决于您想要将参数传递到的具体位置。第一种方法是像原来那样保留 main

object Timer {
def oncePerSecond(callback: => Unit) {
while (true) { callback; Thread sleep 1000 }
}
def timeFlies(x: Int) {
println("time flies like an arrow...")
}
def main(args: Array[String]) {
oncePerSecond(timeFlies(5))
}
}

另一种方法是在回调时传入参数,如下所示:

object Timer {
def oncePerSecond(callback: (Int) => Unit) {
val x = 5
while (true) { callback(x); Thread sleep 1000 }
}
def timeFlies(x: Int) {
println("time flies like an arrow...")
}
def main(args: Array[String]) {
oncePerSecond(timeFlies)
}
}

请注意,timeFlies 具有签名 (Int) => Unit,但 timeFlies(5) 具有签名 =>单位,因为 partial application 。这基本上意味着您可以应用参数来自动创建一个需要更少参数的函数。 oncePerSecond 需要在其签名中知道您是否已将 Int 参数应用于回调。

这两种方法对于不同的用例都有用。第一种方法让 oncePerSecond 不必知道回调的参数。如果需要,第二种方法可以让您每次循环时更改 x 的值。

关于带参数的 Scala 传递函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27433384/

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