在Kotlin中,如何获取数组的前n个元素 [英] In Kotlin, how can I take the first n elements of an array

查看:3602
本文介绍了在Kotlin中,如何获取数组的前n个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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 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() 

还必须调用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆