Adding vararg arrays

I have two classes which have vararg properties of the same type. It is my understanding that vararg simply makes an Array<out T> for the property. I would like to use the plus() function to add two arrays of this type, however I’m having some trouble. This is my current code that does not compile:

fun main(args: Array<String>) {
	val o1 = Obj1("Hello", "World")
	val o2 = Obj2("123", "456")

	o1.stuff + o2.other
}

class Obj1(vararg val stuff: String)
class Obj2(vararg val other: String)

There is no such function that can be called with the arguments supplied. I think I am not fully understanding what exactly it wants.

1 Like

I noticed the other day when I was trying to write a generic function with a vararg parameter that they don’t always seem to act like ‘normal’ arrays. It’s almost as if the compiler knows that they should be treated as an array but doesn’t know what type of array.

Frankly, I have no explanation for this and so I hope something else will be able to enlighten us on the reason for this behavior.

In the meantime, if you need a workaround, then (curiously) converting to lists before doing the addition and then back again to an array compiles and works fine:

fun main(args: Array<String>) {
    val o1 = Obj1("Hello", "World")
    val o2 = Obj2("123", "456")
    val s  = (o1.stuff.asList() + o2.other.asList()).toTypedArray()	       
    println(s.joinToString())
}

class Obj1(vararg val stuff: String)
class Obj2(vararg val other: String)

Try arrayOf and spread operator

fun main(args: Array<String>) {
    val o1 = Obj1("Hello", "World")
    val o2 = Obj2("123", "456")
    val array12 = arrayOf(*o1.stuff, *o2.other)
    array12.forEach{ println(it) }
}

class Obj1(vararg val stuff: String)
class Obj2(vararg val other: String)
1 Like

This is a somewhat unfortunate interaction in the Kotlin type system: https://youtrack.jetbrains.com/issue/KT-16544