코틀린 Interface, Functional Interface

Ham's Velog·2022년 6월 14일
2
post-thumbnail

💡 Kotlin Interface

Interface란?
*추상 메서드의 선언메서드 구현을 모아두는 집합체.

특징?
→ 인터페이스는 상태를 저장 불가. 속성을 가질 수 있지만 추상화하거나 접근자 구현을 제공.

open 키워드가 없이 상속이 되는 이유?
→ 기본적으로 인터페이스의 접근 제한자는 *abstract 이기 때문이다. abstract는 open 키워드가 없어도 상속이 가능하다. 마찬가지로 인터페이스의 멤버 또한 암묵적으로 abstract로 지정이 되어있다.

인터페이스의 멤버?
→ 인터페이스의 멤버는 property / method가 포함되어 있다.
❗ property의 초기화 혹은 위임이 붙은 property의 선언은 불가능❗

  • 추상 메서드 : (영) Abstract Method
    *abstract : 추상적인

✅ Kotlin Interface의 모든것

fun main() {
    val a = Introduce()

    a.PrintPerson()
    a.DefaultMethod()
    a.sameFun()
}

interface Same {
    fun sameFun() = println("Same 인터페이스") // 다른 interface 같은 function
}

interface Person {
    val human: Boolean

    fun sameFun() = println("Person 인터페이스") // 다른 interface 같은 function
}

interface Info: Person { // Person 인터페이스를 상속
    override val human: Boolean
        get() = true // custom getter property

    val name: String
    val age: Int
    val job: String

    fun PrintPerson()

    fun DefaultMethod() = println("Info 인터페이스의 디폴트 메서드") // 디폴트 메서드
}

class Introduce: Info, Same {
    override val name: String = "뇽뇽"
    override val age: Int = 8
    override val job: String = "무직백수고양이"

    override val human: Boolean
        get() = super.human // custom getter property

    override fun PrintPerson() {
        if(human) println("${name}이는 ${age}살 이고, $job 이다.")
    } // Info interface의 PrintPerson() 함수 구현

    override fun sameFun() {
        super<Same>.sameFun()
        super<Info>.sameFun() // 다른 interface 같은 function
    }
}

🤷‍♂️ Functional Interface

📢 Functional Interfce(함수형 인터페이스)란?
→ 오직 하나의 abstract method를 가진 interface
이다. Single Abstract Method Interface 즉 <SAM Interface> 라고 많이 불린다.

💁‍♂️ SAM 변환

fun interface SampleSAM {
    fun Add(a:Int, b:Int): Int
}

fun main() {
 /* val add = object: SampleSAM {
			override fun Add(a:Int, b:Int): Int {
				return a + b
			}
		} */

    val add = SampleSAM { a, b -> a+b }

    println(add.Add(1,3))
}

📢 SAM 변환을 통해 주석의 코드를 단 한 줄의 코드로 바꿔 버릴수도 있다. 이 과정에서 람다식을 이용하기 때문에 코드의 길이를 확 줄일수 있다.


✅ 코틀린의 다른것이 궁금할땐 아래 링크 확인
@evergreen_tree

profile
#안드로이드개발자

1개의 댓글

comment-user-thumbnail
2022년 6월 14일

정말 유익한 내용이네요 감사합니다

답글 달기