function value의 확장은 스칼라의 기초 지식이다.
https://twitter.github.io/scala_school/ko/basics2.html
apply 개념은 다음 예제를 살펴본다.
class IntMultiply {
def apply(t1: Int, t2: Int): Int = (t1*t2)
def apply() = new IntMultiply
}
object IntMultiply extends App {
val multiply = new IntMultiply()
val s = multiply(5,2)
println(s)
}
object IntMultiply extends App {
def apply(t1: Int, t2: Int): Int = (t1*t2)
}
class IntMultiply {
IntMultiply(3,2)
}
아래 익명 함수(function value)는 아래 익명 클래스로 확장(expand)된다.
scala> (x : Int) => x * x
res1: Int => Int = $$Lambda$1034/1553646796@4df39a88
익명 클래스 1)
scala> {
| class AnonFun extends Function1[Int, Int] {
| def apply(x: Int) = x * x
| }
| new AnonFun
| }
res3: Int => Int = <function1>
또는
익명 클래스 2)
scala> new Function1[Int, Int] {
| def apply(x: Int) = x * x
| }
res4: Int => Int = <function1>
따라서 List(1,2)는 List.apply(1,2)가 호출된다.
아래와 같은 함수가 있다고 가정하면..
scala> def f(x: Int): Boolean = ???
f: (x: Int)Boolean
function value는 다음과 같이 사용할 수 있다.
scala> (x: Int) => f(x)
res5: Int => Boolean = $$Lambda$1110/1709317347@6c3659be
클래스로 확장되면 다음과 같다.
scala> new Function1[Int, Boolean] {
| def apply(x : Int) = f(x)
| }
res6: Int => Boolean = <function1>
'scala' 카테고리의 다른 글
[scala] filter류 예제 - filter, filterNot, partition, takeWhile, dropWhile (0) | 2017.06.30 |
---|---|
[scala] mergesort(match) 예제 (0) | 2017.06.29 |
[scala] Boolean-ifThenElse (coursera 강의 발췌) (0) | 2017.06.28 |
[sbt] sbt 버전 확인하기 (0) | 2017.06.26 |
[play2] json-객체 연동 코드 예제 (0) | 2017.06.26 |