Page tree

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagejava
firstline1
titlein, out 위치
collapsetrue
//P는 in의 위치(파라미터로 소비됨), R은 out위치(return 타입으로 제공됨)
interface Function<in P, out R> {
    operator fun invoke(p: P) : R
}


//무공변성
fun <T: R, R> copyData(source: MutableList<T>,
                       destination: MutableList<R>) {
    for (item in source) {
        destination.add(item)
    }
}


//공변성
fun <T> copyData(source: MutableList<out T>,
                 destination: MutableList<T>) {
    for (item in source) {
        destination.add(item)
    }
}


//반공변성
fun <T> copyData(source: MutableList<T>,
                 destination: MutableList<in T>) {
    for (item in source) {
        destination.add(item)
    }
}


fun main(args: Array<String>) {
    val ints = mutableListOf(1, 2, 3)
    val anyItems = mutableListOf<Any>()
    copyData(ints, anyItems)
    println(anyItems)
}


  • star projection : 제네릭 인자에 대한 정보 없음 → List<*>
  • List<Any?>는 어떠한 타입이든 담을 수 있지만, List<*>는 한가지 타입만 담을 수 있다.

...