«   2025/02   »
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
Tags
more
Archives
Today
Total
관리 메뉴

올해는 머신러닝이다.

list(추가 불가능함)에 add 를 달아보자 본문

링크모음/코틀린

list(추가 불가능함)에 add 를 달아보자

행복한 수지아빠 2018. 1. 6. 16:44

fun appendList<T>(listOfLists: List<List<T>>, toAppend: List<T>): List<List<T>> { }

Of course both of the following work:

fun appendList<T>(listOfLists: List<List<T>>, toAppend: List<T>): List<List<T>> {   // Use spread operator   return listOf(*listOfLists.toTypedArray(), toAppend); }

fun appendList<T>(listOfLists: List<List<T>>, toAppend: List<T>): List<List<T>> {
  // Turn to mutable list
  val ret = listOfLists.toArrayList()
  ret.add(toAppend)
  return ret
}


But this is confusing to users who might expect + to work. Due to type erasure, + will always have quirks like this. I had to add the following extension:

operator fun <T, C : Collection<T>> List<C>.plus(toAppend: C): List<C> {
    val ret = java.util.ArrayList<C>(this.size + 1)
    ret.addAll(this)
    ret.add(toAppend)
    return ret
}