티스토리 뷰

Programming/Kotlin

Kotlin Generic

Albothyl 2022. 4. 30. 14:15

Unchecked casts

- 어떤 type이 들어올지 모르는 상황에서 type을 특정해서 사용하면 아래 warn이 발생한다.

Warning: Unchecked cast: `Map<String, *>` to `Map<String, Int>`

- 이 warn은 아래 annotation을 추가하여 제거할 수 있다.

@Suppress("UNCHECKED_CAST")

fun readDictionary(file: File): Map<String, *> = file.inputStream().use {
   TODO("Read a mapping of strings to arbitrary elements.")
}

// We saved a map with `Int`s into this file
val intsFile = File("ints.dictionary")

// Warning: Unchecked cast: `Map<String, *>` to `Map<String, Int>`
val intsDictionary: Map<String, Int> = readDictionary(intsFile) as Map<String, Int>

 

Generic

- For generic functions, using reified type parameters makes casts like arg as T checked, unless arg's type has its own type arguments that are erased. (inline, reified)

- Reified 키워드는 Generics로 inline function에서 사용되며, Runtime에 타입 정보를 알고 싶을 때 사용한다. 언제 이 키워드가 필요할까? Generics 코드를 컴파일할 때 컴파일러는 T가 어떤 타입인지 알고 있다. 하지만 Compile하면서 타입 정보를 제거하여 Runtime에는 T가 어떤 타입인지 모른다. 그냥 T로 정해진 객체가 존재할 뿐이다. Reified 키워드를 사용하면 Generics function에서 Runtime에 타입 정보를 알 수 있다. (주의 inline function과 함께 사용할 때만 사용 가능)

inline fun <reified T> List<*>.asListOfType(): List<T>? =
    if (all { it is T })
        @Suppress("UNCHECKED_CAST")
        this as List<T> else
        null

-------

fun <T> TreeNode.findParentOfType(clazz: Class<T>): T? {
    var p = parent
    while (p != null && !clazz.isInstance(p)) {
        p = p.parent
    }
    @Suppress("UNCHECKED_CAST")
    return p as T?
}

Generic Type Naming Rule

- T, E, K, V, X, T1, T2

 

타입 매개 변수 이름은 통상적으로 단일 문자로 구성하며, 대부분 다음 다섯 개 중 하나에 속한다.

 

- 임의 타입: T, U, T1, T2, T3

- 컬렉션 요소 타입: E

- Map의 Key, Value: K, V

- 예외: X

 

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

Kotlin Function  (0) 2022.05.14
Kotlin Reflection  (0) 2022.04.30
Kotlin Null Safety  (0) 2022.04.23
Kotlin Loop  (0) 2022.04.23
Kotlin Conditions  (0) 2022.04.23
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함