如何在Scala的def块中定义辅助函数?
我想在函数内部创建一个如何在Scala的def块中定义辅助函数?,scala,Scala,我想在函数内部创建一个helper函数,然后调用helper函数,并将其返回函数定义的原始调用 例如: def g(arg1: List[T]): List[T] = { def h(arg1: List[T], arg2: [T]): List[T] = { //code to call here } //call h with an initial value h(arg, 12345) } ... ... //in main() g(List
helper函数
,然后调用helper函数
,并将其返回函数定义的原始调用
例如:
def g(arg1: List[T]): List[T] = {
def h(arg1: List[T], arg2: [T]): List[T] = {
//code to call here
}
//call h with an initial value
h(arg, 12345)
}
...
...
//in main()
g(List(1,2,3)) // --> returns result of h(List(1,2,3), 12345)
我想在原始函数的范围内定义函数,因为它与代码中的其他函数无关
Scala的Scala
方法是什么
是否也有完全不同的方法来创建相同的功能?如果是,怎么做
(我之所以想到这一点,是因为在
OCaml
中使用了let
+范式)scala的方法是:
def g(arg1: List[T]): List[T] = {
def h(arg2: T): List[T] = {
// arg1 is already available here. (closure)
//code to call here
}
//call h with an initial value
h(12345)
}
另一种方法是
val h = new Function1[T, List[T]] {
def apply(arg2: T): List[T] = {
// function, arg1 is still available.
}
}
您可以在编写的其他函数中或多或少地定义本地函数。例如
object LocalFunctionTest {
def g(arg: List[Int]): List[Int] = {
def h(lst: List[Int], i: Int) = {
val l = lst.map(_ + i)
l :+ 3
}
h(arg, 12345)
}
}
scala> LocalFunctionTest.g(List(1,2,3))
res1: List[Int] = List(12346, 12347, 12348, 3)
谢谢,这也帮助我以另一种方式理解闭包。