In Kotlin, how can I take the first n elements of an array

The problem with your code that you create pairs with color constants which are Ints (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 are very close :)

val allColours = arrayOf("red", "blue", "green")
kotlin.io.println(allColours.take(2))

Will give you first two elements ["red", "blue"]

You have to specify the number of elements you want to take from the array


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)

I know you already proposed the usage of take, but alternatively ranges and a simple map also help to write idiomatic code as shown next:

var pegColours = (0 until 3)
    .map { allColours[it] }
    .toTypedArray()

Tags:

Kotlin