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
You are very close :)
Will give you first two elements ["red", "blue"]
You have to specify the number of elements you want to take from the array
The problem with your code that you create pairs with color constants which are
Int
s (allColours
has typeArray<Pair<Int, Int>>)
, but you expectArray<Pair<Color, Color>>
. What you have to do is change typepegColours
type and usetake
:Also you have to call
toTypedArray()
causeArray.take
returnsList
rather thanArray
. Or you can changepegColours
type as following:You need to specify the number of items you want to take.
For a random number of random indices, you can use the following:
Note that you can write an extension method for this:
Alternatively, if the indices are consecutive, you can use slice:
I know you already proposed the usage of
take
, but alternatively ranges and a simplemap
also help to write idiomatic code as shown next: