추상 메소드가 하나만 있는 interface
를 functional interface
또는 SAM(Single Abstract Method) interface
라고 한다.
SAM interfaces
의 경우 람다식을 사용하여 코드를 보다 간결하고 읽기 쉽게 변환할 수 있다. 기존에 Java interface의 경우에만 지원이 됬는데 Kotlin에서도 1.4 버전부터 가능해졌다. 예시를 통해 확인해보자.
SAM interfaces
의 인스턴스를 만드는데 사용할 수 있다.
val runnable = Runnable { println("This runs in a runnable") }
메소드 호출에도 사용할 수 있다.
val executor = ThreadPoolExecutor()
// Java signature: void execute(Runnable command)
executor.execute { println("This runs in a thread pool") }
Kotlin에서 SAM conversions
을 사용하기 위해선 interface
앞에 fun
키워드를 붙여준다.
fun interface IntPredicate {
fun accept(i: Int): Boolean
}
Java에서와 동일하게 사용할 수 있다.
val isEven = IntPredicate { it % 2 == 0 }
Java 클래스를 하나 만들어 준다.
SAM interface
와 interface
를 설정하는 메소드를 만들어 주었다. 그 다음 Kotlin에서 테스트를 진행해 본다.
SAM interfaces
의 인스턴스를 담은 변수와 JavaInterfaceTest
인스턴스를 만든 후 SAM interfaces
를 세팅해줬다. SAM conversions
이 정상적으로 적용된 것을 볼 수 있다.
Kotlin 클래스를 하나 만들어 준다.
위에서 테스트해본 Java 클래스와 비슷하지만 fun
키워드가 있는 KotlinInterfaceFun
와 없는 KotlinInterface
두 가지를 만들어 주었다.
테스트를 진행해 본다.
코드를 살펴보면 fun
키워드가 있는 경우 kotlinInterfaceFun
변수와 setKotlinInterfaceFun
메소드를 확인해보면 SAM conversions
이 정상적으로 적용되었다.
하지만 fun
키워드가 없는 KotlinInterface
의 경우 SAM conversions
이 적용되지 않은 일반적인 방식으로 사용할 수 있었다.
안드로이드 개발을 진행하면서 Java의 SAM interface
를 사용할 때 SAM conversions
을 많이 사용하였는데, Kotlin에서도 1.4버전부터 SAM conversions
을 활용할 수 있기에 내용을 정리해보았다.