In Kotlin, how can I take the first n elements of this array:
val allColours = arrayOf( Pair(Color.RED, Color.WHITE), Pair(Color.RED, Color.BLACK), Pair(Color.YELLOW, Color.BLACK), Pair(Color.GREEN, Color.WHITE), Pair(Color.BLUE, Color.WHITE), Pair(Color.BLUE, Color.WHITE), Pair(Color.CYAN, Color.BLACK), Pair(Color.WHITE, Color.BLACK))
So how can I fill pegColours
with the first say 3 Pairs?
var pegColours: Array<Pair<Color,Color>> = //???
I tried allColours.take
but it gave an error:
Expecting an element
The Take function returns a list containing the first n elements. For example, you have a list of integers starting from 1000 to 10000. Suppose you want the first 15 values from that list. Then, you can use the standard library function take that returns the first specified n elements from the list.
Kotlin has set() and get() functions that can direct modify and access the particular element of array respectively. The set() function is used to set element at particular index location. This is also done with assigning element at array index. Array get() function is used to get element from specified index.
The problem with your code that you create pairs with color constants which are Int
s (allColours
has type Array<Pair<Int, Int>>)
, but you expect Array<Pair<Color, Color>>
. What you have to do is change type pegColours
type and use take
:
var pegColours: Array<Pair<Int, Int>> = allColours.take(3).toTypedArray()
Also you have to call toTypedArray()
cause Array.take
returns List
rather than Array
. Or you can change pegColours
type as following:
var pegColours: List<Pair<Int, Int>> = allColours.take(3)
You need to specify the number of items you want to take.
allColours.take(3)
For a random number of random indices, you can use the following:
val indexes = arrayOf(2, 4, 6) allColours.filterIndexed { index, s -> indexes.contains(index) }
Note that you can write an extension method for this:
fun <T> Array<T>.filterByIndices(vararg indices: Int) = filterIndexed { index, _ -> indices.contains(index) }
Alternatively, if the indices are consecutive, you can use slice:
allColours.slice(1..3)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With