Functional Interface

Java์˜ @Funtional Interface ์ฒ˜๋Ÿผ Kotlin์—์„œ๋„ ํ•˜๋‚˜์˜ ์ถ”์ƒ ๋ฉ”์†Œ๋“œ๋งŒ ๊ฐ€์งˆ ์ˆ˜ ์žˆ๊ฒŒ ๊ฐ•์ œํ•  ์ˆ˜์žˆ์Šต๋‹ˆ๋‹ค.

fun interface SampleInterface {
    fun index(value:Int): String
}

default ๋ฉ”์„œ๋“œ๋Š” ์ œ์™ธ๋ฉ๋‹ˆ๋‹ค.

fun interface SampleInterface {
    fun index(value:Int): String
    fun index(value:String): String = "hello $value"
}

์‚ฌ์šฉ

SAM์„ ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•๊ณผ ์•„๋‹Œ๋ฐฉ๋ฒ•์ด ์กด์žฌํ•ฉ๋‹ˆ๋‹ค โ€ป SAM : ๋žŒ๋‹ค์‹์„ ์ด์šฉํ•œ ๋ณ€ํ™˜

SAM X
fun sample(value: Int) : String = object : SampleInterface {
    override fun index(value: Int): String {
        return "hello $value"
    }
}.index(value)
SAM O
fun sample(value: Int) : String = SampleInterface { "hello $it" }.index(value)

Last updated