Array concatenation: Difference between revisions
Content deleted Content added
added Zig |
→{{header|Kotlin}}: Arrays *do* have a plus operator in kotlin. |
||
Line 2,436: | Line 2,436: | ||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
⚫ | |||
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) |
|||
⚫ | |||
val |
val b = intArrayOf(4, 5, 6) |
||
val b |
val c = a + b // [1, 2, 3, 4, 5, 6] |
||
⚫ | |||
val c: Array<Int> = (a.toList() + b.toList()).toTypedArray() |
|||
⚫ | |||
}</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> |
||