在 Scala 中,函数是一等公民,可以像其他值一样被传递和返回。返回函数引用指的是一个函数返回另一个函数作为其结果。
def createAdder(x: Int): Int => Int = {
(y: Int) => x + y
}
val add5 = createAdder(5)
println(add5(3)) // 输出 8
object MathUtils {
def square(x: Int): Int = x * x
}
def getSquareFunction(): Int => Int = {
MathUtils.square
}
val squareFunc = getSquareFunction()
println(squareFunc(4)) // 输出 16
def createMultiplier(factor: Int): Int => Int = {
def multiplier(x: Int): Int = x * factor
multiplier
}
val double = createMultiplier(2)
println(double(7)) // 输出 14
def createGreeter(greeting: String): String => String = {
(name: String) => s"$greeting, $name!"
}
val helloGreeter = createGreeter("Hello")
println(helloGreeter("Scala")) // 输出 "Hello, Scala!"
var counter = 0
def createCounter(): () => Int = {
() => { counter += 1; counter }
}
风险:多个返回的函数共享同一个可变状态
解决方案:使用不可变状态或为每个函数创建独立状态
def createCounter(): () => Int = {
var localCounter = 0
() => { localCounter += 1; localCounter }
}
// 编译错误:缺少参数类型
def createFunction() = x => x * 2
解决方案:明确指定类型
def createFunction(): Int => Int = x => x * 2
返回函数可能涉及闭包创建,对性能敏感的场景需注意。
优化方案:对于简单函数,可以使用方法引用而非闭包
def createComparator[T](ordering: Ordering[T]): (T, T) => Boolean = {
ordering.lt
}
Scala 的函数返回机制是其函数式编程能力的核心部分,合理使用可以大幅提高代码的表达力和灵活性。
没有搜到相关的文章