Array<T>.plus() should be Array<out T>.plus()?


#1
val arr: Array<out CharSequence> = TODO()
val arr2: Array<CharSequence> = arr.plus("test")    //error

my solution:

operator fun <T> Array<out T>.plus(element: T): Array<T> {
    val index = size
    val result = Arrays.copyOf(this, index + 1)
    result[index] = element
    return result
}

#2

Please consider the situation:

val arr: Array<out CharSequence> = arrayOf("a")
val arr2 = arr + StringBuilder("b")

Given that Arrays.copyOf creates a copy with the same element type, you won’t be able to put a StringBuilder in an array of strings.