Array concatenation: Difference between revisions

Content added Content deleted
(added Zig)
(→‎{{header|Kotlin}}: Arrays *do* have a plus operator in kotlin.)
Line 2,436: Line 2,436:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<syntaxhighlight lang="kotlin">fun main() {
There is no operator or standard library function for concatenating <code>Array</code> types. One option is to convert to <code>Collection</code>s, concatenate, and convert back:
val a = intArrayOf(1, 2, 3)
<syntaxhighlight lang="kotlin">fun main(args: Array<String>) {
val a: Array<Int> = arrayOf(1, 2, 3) // initialise a
val b = intArrayOf(4, 5, 6)
val b: Array<Int> = arrayOf(4, 5, 6) // initialise b
val c = a + b // [1, 2, 3, 4, 5, 6]
println(c.contentToString())
val c: Array<Int> = (a.toList() + b.toList()).toTypedArray()
println(c)
}</syntaxhighlight>

Alternatively, we can write our own concatenation function:
<syntaxhighlight lang="kotlin">fun arrayConcat(a: Array<Any>, b: Array<Any>): Array<Any> {
return Array(a.size + b.size, { if (it in a.indices) a[it] else b[it - a.size] })
}</syntaxhighlight>

When working directly with <code>Collection</code>s, we can simply use the <code>+</code> operator:
<syntaxhighlight lang="kotlin">fun main(args: Array<String>) {
val a: Collection<Int> = listOf(1, 2, 3) // initialise a
val b: Collection<Int> = listOf(4, 5, 6) // initialise b
val c: Collection<Int> = a + b
println(c)
}</syntaxhighlight>
}</syntaxhighlight>