웹사이트 검색

코틀린 봉인 클래스


이 튜토리얼에서는 Kotlin Sealed Class를 살펴보겠습니다. 그들은 무엇인가? 그들의 용도는 무엇입니까? 아래에서 이러한 모든 사항을 다룰 것입니다.

코틀린 봉인 클래스

Kotlin Sealed 클래스 구현

Kotlin의 봉인된 클래스는 다음과 같은 방식으로 구현됩니다.

sealed class A{
    class B : A()
    class C : A()
}

봉인된 클래스를 지정하려면 봉인된 한정자를 추가해야 합니다. 봉인된 클래스는 인스턴스화할 수 없습니다. 따라서 암묵적으로 추상적입니다. 다음은 작동하지 않습니다.

fun main(args: Array<String>) 
{
    var a = A() //compiler error. Class A cannot be instantiated.
}

봉인된 클래스의 생성자는 기본적으로 비공개입니다. 봉인된 클래스의 모든 하위 클래스는 동일한 파일 내에서 선언되어야 합니다. 봉인된 클래스는 컴파일 타임에만 형식 집합을 제한하여 형식 안전성을 보장하는 데 중요합니다.

sealed class A{
    class B : A() 
    {
        class E : A() //this works.
    }
    class C : A()

    init {
        println("sealed class A")
    }

}

class D : A() //this works
{
class F: A() //This won't work. Since sealed class is defined in another scope.
}

생성자를 사용하여 봉인된 클래스 만들기.

sealed class A(var name: String){
    class B : A("B")
    class C : A("C")
}

class D : A("D")
fun main(args: Array<String>) {
    
    var b = A.B()
    var d = D()
}

봉인된 클래스에 개체 추가.

fun main(args: Array<String>) {

    val e = A.E("Anupam")
    println(e) //prints E(name=Anupam)

    var d = A.D
    d.name() //prints Object D
}


sealed class A{
    class B : A()
    class C : A()
    object D : A()
    {
         fun name()
         {
             println("Object D")
         }
    }
    data class E(var name: String) : A()

}

열거형 클래스와 봉인 클래스의 차이점

Kotlin에서 Sealed 클래스는 스테로이드의 Enum 클래스라고 할 수 있습니다. 봉인된 클래스를 사용하면 모든 enum 상수에 대해 동일한 유형을 사용하도록 제한하는 Enum과 달리 다른 유형의 인스턴스를 만들 수 있습니다. 다음은 Enum 클래스에서 불가능합니다.

enum class Months(string: String){
January("Jan"), February(2),
}

Enum 클래스는 모든 상수에 대해 단일 유형만 허용합니다. 여기에서 봉인된 클래스가 여러 인스턴스를 허용함으로써 우리를 구할 수 있습니다.

sealed class Months {
    class January(var shortHand: String) : Months()
    class February(var number: Int) : Months()
    class March(var shortHand: String, var number: Int) : Months()
}

프로젝트에서 Sealed 클래스의 이 기능을 어떻게 사용할 수 있습니까? 애플리케이션과 같은 뉴스피드에서 아래와 같이 상태, 이미지, 비디오 게시물에 대한 세 가지 클래스 유형을 만들 수 있습니다.

sealed class Post
{
    class Status(var text: String) : Post()
    class Image(var url: String, var caption: String) : Post()
    class Video(var url: String, var timeDuration: Int, var encoding: String): Post()
}

Enum 클래스에서는 불가능합니다.

봉인된 수업 및 시기

봉인된 클래스는 각각의 하위 클래스와 해당 유형이 사례 역할을 하므로 일반적으로 when 문과 함께 사용됩니다. 또한 Sealed 클래스가 유형을 제한한다는 것을 알고 있습니다. 따라서 when 문의 else 부분은 쉽게 제거할 수 있습니다. 다음 예제는 동일한 내용을 보여줍니다.

sealed class Shape{
    class Circle(var radius: Float): Shape()
    class Square(var length: Int): Shape()
    class Rectangle(var length: Int, var breadth: Int): Shape()
}

fun eval(e: Shape) =
        when (e) {
            is Shape.Circle -> println("Circle area is ${3.14*e.radius*e.radius}")
            is Shape.Square -> println("Square area is ${e.length*e.length}")
            is Shape.Rectangle -> println("Rectagle area is ${e.length*e.breadth}")
        }

아래와 같이 main 함수에서 eval 함수를 실행해 봅시다.

fun main(args: Array<String>) {

    var circle = Shape.Circle(4.5f)
    var square = Shape.Square(4)
    var rectangle = Shape.Rectangle(4,5)

    eval(circle)
    eval(square)
    eval(rectangle)
    //eval(x) //compile-time error.

}

//Following is printed on the console:
//Circle area is 63.585
//Square area is 16
//Rectangle area is 20

참고: is 수정자는 클래스가 다음 유형인지 확인합니다. is 수정자는 클래스에만 필요합니다. 아래와 같이 Kotlin 객체에는 사용할 수 없습니다.

sealed class Shape{
    class Circle(var radius: Float): Shape()
    class Square(var length: Int): Shape()
    object Rectangle: Shape()
    {
        var length: Int = 0
        var breadth : Int = 0
    }
}

fun eval(e: Shape) =
        when (e) {
            is Shape.Circle -> println("Circle area is ${3.14*e.radius*e.radius}")
            is Shape.Square -> println("Square area is ${e.length*e.length}")
            Shape.Rectangle -> println("Rectangle area is ${Shape.Rectangle.length*Shape.Rectangle.breadth}")
        }

이것으로 kotlin 봉인된 클래스 자습서가 끝납니다. 참조: Kotlin 문서