phantasmicmeans 기술 블로그

10. Kotlin - Functional Interface 본문

Programming/Kotlin

10. Kotlin - Functional Interface

phantasmicmeans 2021. 1. 22. 12:57

Functional (SAM) Interface

  • SAM: Single Abstract Method

자바에서도 마찬가지로 하나의 abstract method를 가지는 인터페이스를 functional interface라 하고 코틀린도 마찬가지이다.

functional interface 를 선언하려면 fun modifier를 사용하면 된다.

fun interface KRunnable {
  fun invoke() 
}

SAM Conversions

이것도 자바와 동일하게 람다식을 활용하면 된다. 자바 Functional Interface를 알고 있다면 아주 쉽게 이해 될 것이다.

functional interface

fun interface IntPredicate {
  fun accept(i: Int): Boolean
}

not sam conversion

val isEven = object: IntPredicate {
  override fun accept(i: Int): Boolean {
    return i % 2 == 0
  }
}

sam conversion

val isEven = IntPredicate { it % 2 == 0 } 

더 자세한 사항: https://www.baeldung.com/kotlin/lambda-expressions

'Programming > Kotlin' 카테고리의 다른 글

12. Kotlin - Extension Function VS Function literal with receiver  (0) 2021.01.22
11. Kotlin - Higher Order Functions  (0) 2021.01.22
9. Kotlin - Interface  (0) 2021.01.22
8. Kotlin - Backing Field  (0) 2021.01.22
7. Kotlin - Properties  (0) 2021.01.22
Comments