탐비의 개발 낙서장

[Kotlin] 코틀린 제네릭(Generics)과 타입 파라미터 제약 본문

프로그래밍/Kotlin

[Kotlin] 코틀린 제네릭(Generics)과 타입 파라미터 제약

탐비_ 2021. 7. 19. 23:48

 

Geneics(제네릭)

 

클래스나 인터페이스 혹은 함수 등에서 동일한 코드로 여러 타입을 지원하게 해주는 기능

 

 T는 타입 파라미터로, 클래스의 인스턴스를 생성할 때, type argument를 제공해야 한다.

 

class Box<T>(t: T) {
	var value = t
}

 

  1. <Int> 형태로 명시하는 방법이 있고

  2. 생성자 등에서 추론 가능하게 하는 방법이 있다.

 

val box: Box<Int> = Box<Int>(1) // Using type argument

val box = Box(1) // Type Inferred

 

 

 

타입 파라미터 제약

 

 클래스의 경우, 멤버 함수가 해당 타입에 대한 반복 또는 비교가 필요 할 경우

 타입 파라미터에 제약을 걸어 줄 필요가 있다.

 

class Set<T>(elements: List<T>)
{
    private var elements = mutableListOf<T>()

    init {
        elements.toMutableList()
        this.elements = elements.distinct() as MutableList<T>
    }
    
    // ...
    
    fun getSorted(): List<T> {
        return elements.sorted()
    }
}

 

 상단의 코드를 실행하면, sorted() 함수에서 다음과 같은 에러가 발생한다.

 

제네릭 Type mismatch 에러 발생

 

 sorted 함수는 Comparable을 상속받은 Type만 적용할 수 있기 때문에 발생하는 에러임.

 

class Set<T: Comparable<T>>(elements: List<T>)
{
    private var elements = mutableListOf<T>()

    init {
        elements.toMutableList()
        this.elements = elements.distinct() as MutableList<T>
    }
    
    // ...
    
    fun getSorted(): List<T> {
        return elements.sorted()
    }
}

 

위와 같이 T에 Comparable 한정자를 지정해주면 비교 가능한 타입만 입력할 수 있게 되어 정상 실행 된다.

 

 

References

https://kotlinlang.org/docs/generics.html#variance 코틀린 제네릭 가이드