在Kotlin中,如何获取数组的前n个元素 [英] In Kotlin, how can I take the first n elements of an array
问题描述
在Kotlin中,如何获取该数组的前n个元素:
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))
那么我该如何用第一个说的3对来填充pegColours
?
So how can I fill pegColours
with the first say 3 Pairs?
var pegColours: Array<Pair<Color,Color>> = //???
我尝试了allColours.take
,但它给出了一个错误:
I tried allColours.take
but it gave an error:
期待元素
推荐答案
使用颜色常量为Int
s(allColours
的类型为Array<Pair<Int, Int>>)
,但期望为Array<Pair<Color, Color>>
)创建的配对代码的问题>.您要做的就是更改pegColours
类型并使用take
:
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()
还必须调用toTypedArray()
,因为Array.take
返回List
而不是Array
.或者,您可以按以下方式更改pegColours
类型:
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)
这篇关于在Kotlin中,如何获取数组的前n个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!