Array concatenation: Difference between revisions

→‎{{header|Kotlin}}: Arrays *do* have a plus operator in kotlin.
(added Zig)
(→‎{{header|Kotlin}}: Arrays *do* have a plus operator in kotlin.)
Line 2,436:
 
=={{header|Kotlin}}==
<syntaxhighlight lang="kotlin">fun main(args: Array<String>) {
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>b = arrayOfintArrayOf(14, 25, 36) // initialise a
val c = a + b: Array<Int>// =[1, 2, 3, arrayOf(4, 5, 6) // initialise b]
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>
 
32

edits