Hanbit the Developer

Kotlin Documentation | Functional (SAM) interfaces 본문

Kotlin

Kotlin Documentation | Functional (SAM) interfaces

hanbikan 2023. 5. 22. 17:53

Kotlin Documentation 시리즈에 대해

Category: Concepts - Classes and objects

문서 링크: https://kotlinlang.org/docs/fun-interfaces.html


Functional interface or Single Abstract Method (SAM) interface

non-abstract members를 여러 개 가질 수 있으나 abstract member는 1개만 가질 수 있다:

fun interface OnClickListener {
   fun onClick(i: Int): Boolean
}

SAM conversions

  • without a SAM conversion
// Creating an instance of a class
val isEven = object : OnClickListener {
   override fun onClick(i: Int): Boolean {
       return i % 2 == 0
   }
}
  • with a SAM conversion
// Creating an instance using lambda
val isEven = OnClickListener { it % 2 == 0 }

vs typealias

typealias IntPredicate = (i: Int) -> Boolean
  • typealias는 새 타입을 만드는 것은 아님
  • 추가적인 non-abstract 함수를 가질 수 없음
  • 다만 문법적으로, 그리고 런타임에서 더 가벼움

'Kotlin' 카테고리의 다른 글

Kotlin Documentation | Extensions  (0) 2023.05.22
Kotlin Documentation | Visibility modifiers  (0) 2023.05.22
Kotlin Documentation | Interfaces  (0) 2023.05.22
Kotlin Documentation | Properties  (0) 2023.05.22
Kotlin Documentation | Inheritance  (0) 2023.05.22