Kotlin/포스팅

코틀린 인터페이스 봉인

짜집퍼박사(짜박) 2024. 1. 2. 20:33

코틀린 1.5 버전부터 인터페이스에도 봉인(Sealed)을 적용할 수 있습니다. 봉인된 인터페이스는 특정 인터페이스를 구현하는 클래스를 제한하는 역할을 합니다. 이를 통해 인터페이스의 상속을 더욱 명시적으로 관리할 수 있게 되었습니다.

 

봉인된 인터페이스 선언

봉인된 인터페이스는 sealed 키워드를 사용하여 선언됩니다.

sealed interface MySealedInterface {
    fun method(): String
}

 

봉인된 인터페이스의 사용

봉인된 인터페이스를 사용하는 클래스에서는 해당 인터페이스의 하위 클래스를 명시적으로 선언해야 합니다.

class MyClass1 : MySealedInterface {
    override fun method(): String {
        return "Implementation 1"
    }
}

class MyClass2 : MySealedInterface {
    override fun method(): String {
        return "Implementation 2"
    }
}

 

봉인된 인터페이스와 when 식

when 식을 사용할 때, 봉인된 인터페이스를 구현한 클래스의 모든 경우에 대한 처리가 필요합니다.

fun processInterface(myInterface: MySealedInterface): String {
    return when (myInterface) {
        is MyClass1 -> "Class 1: ${myInterface.method()}"
        is MyClass2 -> "Class 2: ${myInterface.method()}"
    }
}

 

봉인된 인터페이스와 상속 구조

봉인된 인터페이스는 상속을 통한 확장이 가능합니다. 새로운 하위 인터페이스를 추가할 때는 해당 인터페이스를 봉인된 인터페이스의 하위로 명시적으로 선언해야 합니다.

sealed interface MySealedInterface {
    fun method(): String
}

interface MyExtendedInterface : MySealedInterface {
    fun additionalMethod(): String
}

이후에는 새로운 클래스에서 이 확장된 인터페이스를 구현할 수 있습니다.

class MyClass3 : MyExtendedInterface {
    override fun method(): String {
        return "Implementation 3"
    }

    override fun additionalMethod(): String {
        return "Additional method implementation"
    }
}

 

주의사항

1. 봉인된 인터페이스는 동일한 파일 내에서만 정의될 수 있습니다.
2. 봉인된 인터페이스의 하위 클래스는 봉인된 인터페이스를 구현하는 클래스 내에서 정의되어야 합니다.

// 컴파일 에러: Sealed interfaces can only be defined in a file with the same name as the interface
// or in the file with the `typealias` for this interface
interface AnotherSealedInterface

봉인된 인터페이스는 특정 인터페이스의 하위 클래스를 명시적으로 제한하고, 코드를 더욱 안정적으로 만드는 데 도움을 줍니다. 이는 특히 라이브러리나 프레임워크에서 특정 인터페이스를 사용하는 클래스의 확장을 제어하고자 할 때 유용합니다.

 

With ChatGPT

'Kotlin > 포스팅' 카테고리의 다른 글

코틀린 타입 파라미터  (0) 2024.01.02
코틀린 제네릭스  (0) 2024.01.02
코틀린 봉인된 클래스  (0) 2024.01.02
코틀린 인터페이스  (0) 2024.01.02
코틀린 추상클래스의 추상 멤버  (0) 2024.01.02