phantasmicmeans 기술 블로그

9. Kotlin - Interface 본문

Programming/Kotlin

9. Kotlin - Interface

phantasmicmeans 2021. 1. 22. 12:56

Interfaces

코틀린의 인터페이스는 abstract method 뿐만 아니라 java의 default method 처럼 구현 된 메소드를 포함할 수 있고, 프로퍼티 또한 포함할 수 있다.
다만 이 프로퍼티는 state를 유지하진 못하기에 구현체에서 접근자를 통해 컨트롤해야한다.

interface MyInterface {
  fun bar() 
  fun foo() {
    // optional body 
  } 
}

Implementing Interfaces

class Child : MyInterface {
  override fun bar() {
    // body
  }

Properties in Interfaces

인터페이스에도 프로퍼티를 선언할 수 있다고 했다. 해당 프로퍼티는 abstract 이거나, 구현체에서 접근자를 통해 제공해야한다.
또한 인터페이스 내의 프로퍼트는 Backing Field를 가질 수 없으므로 interface 내의 접근자에서 field를 사용하는 것은 의미가 없다.

interface MyInterface {
  val prop: Int // abstract

  val propertyWithImplementation: String 
    get() = "foo"

  fun foo() {
    print(prop)
  }
}

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

Resolving overriding confilicts

interface A {
    fun foo() { print("A") } // implemented 
    fun bar() // abstract 
}

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

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 A와 B는 동일한 이름의 function을 포함한다. 특정 인터페이스의 메소드를 사용하고자 한다면 super<T>.~() 를 사용하면 된다.

'Programming > Kotlin' 카테고리의 다른 글

11. Kotlin - Higher Order Functions  (0) 2021.01.22
10. Kotlin - Functional Interface  (0) 2021.01.22
8. Kotlin - Backing Field  (0) 2021.01.22
7. Kotlin - Properties  (0) 2021.01.22
6. Kotlin - Class Inheritance  (0) 2021.01.22
Comments