I can't seem to find a right solution. Trying to add a list of array to another array. With my Python background it is easily done but not in Kotlin.
fun main() {
val even = arrayOf(2, 4, 6)
val odd = arrayOf(1, 3, 5)
val arr1 = arrayOf(even, odd)
val extra = arrayOf(7,7,7)
val arr2 = arrayOf(arr1, extra)
print(arr2.contentDeepToString())
}
When executing above code I receive...
[[[2, 4, 6], [1, 3, 5]], [7, 7, 7]]
What I want to achieve is this ....
[2, 4, 6], [1, 3, 5], [7, 7, 7]
CodePudding user response:
To add a thing to an array of things, and produce a new array, use plusElement
:
val arr2 = arr1.plusElement(extra)
This not only works for arrays, but also works for any Iterable
s, i.e. List
s, Set
s etc.
CodePudding user response:
Do you get why you're getting that result? arrayOf(items)
creates a new array wrapping those items, so arrayOf(even, odd)
is an array that contains two arrays. Then you create another array, containing that array-of-arrays and another single array. You're nesting them as you go
Sweeper's answer is probably what you want, but there are a lot of ways to combine collections, flatten sequences etc. Like one thing you can do is use the *
operator (the "spread operator") to "unpack" your arrays, so you get the items instead:
// unpack arr1 from an array of arrays, into just those arrays
// equivalent to arrayOf([2, 4, 6], [1, 3, 5], extra)
val arr2 = arrayOf(*arr1, extra)
print(arr2.contentDeepToString())
>> [[2, 4, 6], [1, 3, 5], [7, 7, 7]]
There's also flatMap
, flatten
etc - the best option depends on what you're doing!
Also when you say you want this:
[2, 4, 6], [1, 3, 5], [7, 7, 7]
that's just a bunch of values, not contained in anything, so we're assuming you want this:
[[2, 4, 6], [1, 3, 5], [7, 7, 7]]
where they're held in an array (or it could be a list). You could use the spread operator to unpack that into a bunch of values, but all you can do with that is pass it as a variable number of arguments to a function (which is what's happening in arrayOf
)
CodePudding user response:
I assume you want to get the following array:
[[2, 4, 6], [1, 3, 5], [7, 7, 7]]
There is an overridden
(plus) operator for Array
s in Kotlin, you can use it for adding arrays:
val arr2 = arr1 extra
Resulting array arr2
will contain all elements of the original array arr1
and then all elements of the array extra
.