Programming Language/Kotlin

[Kotlin] Interfaces

개발왕 금골드 2023. 2. 12. 15:08
반응형

설명

  • 코틀린 인터페이스는 추상 멤버와 구현체를 모두 포함할 수 있다.
  • abstract와의 차이점은 인터페이스 안에 상태를 저장할 수 없다.
  • properties는 가질 수 있지만 abstract이거나 접근 구현체(accessor implementations)를 제공해야 한다.
interface MyInterface {
    fun bar()
    fun foo() {
      // optional body
    }
}


Properties in interfaces

  • 인터페이스 안에 properties를 선언할 수 있다.
  • 인터페이스 안에 선언된 property는 backing field를 가질 수 없다.
interface MyInterface {
    val prop: Int // abstract

    val propertyWithImplementation: String
        get() = "foo"

    fun foo() {
        print(prop)
    }
}

class Child : MyInterface {
    override val prop: Int = 29
}


Interfaces Inheritance

  • 인터페이스는 다른 인터페이스로부터 파생될 수 있다.
  • 이러한 인터페이스를 정의하는 클래스는 오직 해당 인터페이스의 구현체를 정의하는 것을 필요로 한다.
interface Named {
    val name: String
}

interface Person : Named {
    val firstName: String
    val lastName: String

    override val name: String get() = "$firstName $lastName"
}

data class Employee(
    // implementing 'name' is not required
    override val firstName: String,
    override val lastName: String,
    val position: Position
) : Person


Resolving overriding conflicts

interface A {
    fun foo() { print("A") }
    fun bar()
}

interface B {
    fun foo() { print("B") }
    fun bar() { print("bar") }
}

class C : A {
    override fun bar() { print("bar") }
}

class D : A, B {
    override fun foo() {
        super<A>.foo()
        super<B>.foo()
    }

    override fun bar() {
        super<B>.bar()
    }
}
  • 부모 interface의 타입을 정의하여 충돌을 피할 수 있다.



Kotlin Docs 번역
참고자료 : 
Interfaces | Kotlin

Interfaces | Kotlin

kotlinlang.org

 

반응형