본문 바로가기

Development/Programming

[Scala] Nested Functions

스칼라에서는 내부 함수??를 만들어서 사용이 가능하다. 말보단 코드로...


  1. object FilterTest extends App {
  2. def filter(xs: List[Int], threshold: Int) = {
  3. def process(ys: List[Int]): List[Int] =
  4. if (ys.isEmpty) ys
  5. else if (ys.head < threshold) ys.head :: process(ys.tail)
  6. else process(ys.tail)
  7. process(xs)
  8. }
  9. println(filter(List(1, 9, 2, 8, 3, 7, 4), 5))
  10. }


filter라는 함수 내부에 process라는 함수가 정의 되어있고 process는 상황별로 재귀 호출이 되도록 구현이 되어져 있다.

위의 코드를 실행하게 되면 아래와 같은 결과가 나오게 된다.


  1. List(1,2,3,4)