๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

๋นˆ ๊ตฌ๋ฉ ์ฑ„์šฐ๊ธฐ

[Kotlin] Functional (SAM) interface

kotlinlang.org/docs/fun-interfaces.html#sam-conversions

 

Functional (SAM) interfaces | Kotlin

 

kotlinlang.org

์ถ”์ƒ ํ•จ์ˆ˜ ํ•˜๋‚˜๋งŒ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ functional interface, ๋˜๋Š” Single Abstract Method (SAM) interface๋ผ๊ณ  ๋ถ€๋ฅธ๋‹ค. ์ด ์ธํ„ฐํŽ˜์ด์Šค๋Š” ์—ฌ๋Ÿฌ non-abstarct ๋ฉค๋ฒ„๋“ค์„ ๊ฐ€์งˆ ์ˆ˜ ์žˆ์œผ๋‚˜, ์ถ”์ƒ ํ•จ์ˆ˜๋Š” ํ•˜๋‚˜๋งŒ ๊ฐ€์ง„๋‹ค.

 

fun ์ˆ˜์ •์ž๋ฅผ ์ด์šฉํ•ด์„œ ํ‘œ์‹œํ•œ๋‹ค. > fun interface

fun interface KRunnable {
   fun invoke()
}

SAM conversions

SAM coversions๋ฅผ ์ด์šฉํ•˜๋ฉด ๋žŒ๋‹ค ํ‘œํ˜„์‹์„ ์ด์šฉํ•ด์„œ ์ฝ”๋“œ๋ฅผ ๋” ๊ฐ„๊ฒฐํ•˜๊ณ  ์ผ๊ธฐ ์‰ฝ๊ฒŒ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค.

 

์ˆ˜๋™์œผ๋กœ functional interface๋ฅผ ๊ตฌํ˜„ํ•˜๊ธฐ ๋ณด๋‹ค๋Š”, ๋žŒ๋‹ค ํ‘œํ˜„์‹์„ ์“ธ ์ˆ˜ ์žˆ๋‹ค. SAM conversion์„ ์“ฐ๋ฉด, ์ฝ”ํ‹€๋ฆฐ์€ ์ธํ„ฐํŽ˜์ด์Šค๊ฐ€ ๊ฐ€์ง„ ํ•œ ๊ฐœ์˜ ๋ฉ”์†Œ๋“œ์˜ ์„œ๋ช…๊ณผ ์ผ์น˜ํ•˜๋Š” ์„œ๋ช…์„ ๊ฐ€์ง„ ๋žŒ๋‹คํ‘œํ˜„์‹์„ ๊ทธ ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ๊ตฌํ˜„ํ•œ ํด๋ž˜์Šค์˜ ์ธ์Šคํ„ด์Šค๋กœ ๋ณ€ํ™˜์‹œํ‚จ๋‹ค.

 

์˜ˆ๋ฅผ ๋“ค์–ด์„œ, ๋‹ค์Œ Kotlin function interface๋ฅผ ์ƒ๊ฐํ•ด๋ณด์ž.

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

SAM conversion์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š”๋‹ค๋ฉด, ์ฝ”๋“œ๋ฅผ ์ด๋ ‡๊ฒŒ ์จ์•ผ ํ•œ๋‹ค.

// Creating an instance of a class
val isEven = object : IntPredicate {
   override fun accept(i: Int): Boolean {
       return i % 2 == 0
   }
}

Kotlin์˜ SAM conversion์„ ํ™œ์šฉํ•˜๋ฉด, ์•„๋ž˜์ด ๋™์ผํ•œ ์ฝ”๋“œ๋ฅผ ์“ธ ์ˆ˜ ์žˆ๋‹ค.

// Creating an instance using lambda
val isEven = IntPredicate { it % 2 == 0 }

์งง์€ ๋žŒ๋‹ค ํ‘œํ˜„์‹์ด ๋ชจ๋“  ๋ถˆํ•„์š”ํ•œ ์ฝ”๋“œ๋ฅผ ์ œ๊ฑฐํ•œ๋‹ค.

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

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

fun main() {
   println("Is 7 even? - ${isEven.accept(7)}")
}

๊ฒฐ๊ณผ

Is 7 even? - false

Functional interface vs. type aliases

Functional interface์™€ type aliases๋Š” ๋‹ค๋ฅธ ๋ชฉ์ ์œผ๋กœ ์“ฐ์ธ๋‹ค. Type aliase๋Š” ์กด์žฌํ•˜๋Š” ํƒ€์ž…์˜ ์ด๋ฆ„๋“ค๋กœ, ์ƒˆ๋กœ์šด ํƒ€์ž…์„ ๋งŒ๋“ค์–ด๋‚ด์ง€ ์•Š์œผ๋‚˜, functional interface๋Š” ์ƒˆ๋กœ์šด ํƒ€์ž…์„ ๋งŒ๋“ค์–ด๋‚ธ๋‹ค. 

 

Type aliase๋Š” ์˜ค์ง ํ•œ ๋ฉค๋ฒ„๋งŒ ๊ฐ€์ง€๊ณ , functional interface๋Š” ์—ฌ๋Ÿฌ non-abstract ๋ฉค๋ฒ„์™€ ํ•˜๋‚˜์˜ ์ถ”์ƒ ๋ฉค๋ฒ„๋ฅผ ๊ฐ€์ง„๋‹ค. Functional interface๋Š” ๋˜ํ•œ ๋‹ค๋ฅธ ์ธํ„ฐํŽ˜์ด์Šค๋“ค์„ ์ƒ์†๋ฐ›์„ ์ˆ˜ ์žˆ๋‹ค.

 

์œ„์˜ ๊ฒƒ๋“ค์„ ๊ณ ๋ คํ•  ๋•Œ, functional interface๊ฐ€ type aliase๋ณด๋‹ค ๋” ์œ ์—ฐํ•˜๊ณ  ๋” ๋งŽ์€ ๊ธฐ๋Šฅ์„ ๊ฐ€์ง€๊ณ  ์žˆ๋‹ค. 

'๋นˆ ๊ตฌ๋ฉ ์ฑ„์šฐ๊ธฐ' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[Android/Crashlytics] libc.so / unknown ์ด์Šˆ - native crash  (0) 2021.03.29
[Kotlin] Companion Object์˜ ํ™œ์šฉ  (0) 2021.03.29
[Kotlin] Companion objects  (0) 2021.03.29
[์šฉ์–ด] sideload  (0) 2021.03.26
[Kotlin] Sequence  (0) 2021.03.26