링크모음/코틀린
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
}
반응형