Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 445
Dave Chambers Avatar asked Feb 07 '18 15:02

Dave Chambers


People also ask

How do you get the first N elements of a list in Kotlin?

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.

How do I get the value of an array in Kotlin?

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.


2 Answers

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) 
like image 166
hluhovskyi Avatar answered Sep 22 '22 21:09

hluhovskyi


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) 
like image 22
m0skit0 Avatar answered Sep 19 '22 21:09

m0skit0