Scala:返回对函数的引用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3363459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scala: return reference to a function
提问by mariosangiorgio
I'd like to have a Scala functions that returns the reference to another function, is that possible?
我想要一个 Scala 函数来返回对另一个函数的引用,这可能吗?
回答by Thomas
You can return a function type (this is defined by A => B). In this case Int to Int:
您可以返回一个函数类型(由 定义A => B)。在这种情况下,Int 到 Int:
scala> def f(x:Int): Int => Int = { n:Int => x + n }
f: (x: Int)(Int) => Int
When you call the function you get a new function.
当您调用该函数时,您将获得一个新函数。
scala> f(2)
res1: (Int) => Int = <function1>
Which can be called as a normal function:
可以作为普通函数调用:
scala> res1(3)
res2: Int = 5
回答by olle kullberg
One way (somewhat unique to functional object-orientation) you can use higher order functions is to create loose couplings between objects.
可以使用高阶函数的一种方法(对于函数式面向对象有些独特)是在对象之间创建松散耦合。
In the example below the class Alarmhas a method check4Danger()that checks if a calculated value exceeds the DangerLevel. The Alarm class does not know anything about the objects that call it.
在下面的示例中,该类Alarm有一个方法check4Danger()来检查计算值是否超过DangerLevel. Alarm 类对调用它的对象一无所知。
The Carclass has a method engineCrashRisk()that returns an anonymous function that calculate the risk of engine crash. Cardoes not have dependency to Alarm.
本Car类有一个方法engineCrashRisk(),它返回计算引擎崩溃的风险匿名函数。Car不依赖于警报。
case class Alarm(temperature: Double, pressure: Double){
val DangerLevel = 100000.0
def check4Danger( f: (Double, Double) => Double): Boolean = {
val risk = f(temperature, pressure)
if( risk > DangerLevel ){
println("DANGER: "+ risk )
true
}else{
println("Safe: " + risk)
false
}
}
}
case class Car(fuelRate: Double, milage: Int){
def engineCrashRisk() =
(temperature: Double, pressure: Double) =>
temperature * milage + 2*pressure / fuelRate
}
val car = Car(0.29, 123)
val riskFunc = car.engineCrashRisk
val alarm = Alarm(124, 243)
val risk = alarm.check4Danger(riskFunc)
The output of this script is:
这个脚本的输出是:
Safe: 16927.862068965518
In this example we used anonymous functions with closures to create a dependency free method call between the Alarmand Carobjects. Does this example make any sense?
在这个例子中,我们使用带有闭包的匿名函数来创建Alarm和Car对象之间的无依赖方法调用。这个例子有意义吗?

