In Kotlin, how can I take the first n elements of an 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)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)