如何在Scala中定义def块内的辅助函数?

时间:2013-12-01 09:01:41

标签: scala helper-functions

我想在函数内部创建helper function,然后调用helper function并返回函数定义的原始调用。

例如:

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这样做的方式是什么?

是否还有一种完全不同的方式来创建相同的功能?如果是这样,怎么样?

(由于let中使用的in + OCaml范例,我想到了这一点

2 个答案:

答案 0 :(得分:3)

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.
    }
}

答案 1 :(得分:3)

您可以在编写时或多或少地定义其他函数内的本地函数。 E.g。

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)