如何用范围填充可变参数? [英] How to fill varargs with range?

查看:86
本文介绍了如何用范围填充可变参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

填充可变参数的正确方法是什么?我的尝试看起来像是一次小事 拳头我构筑范围
然后我将其转换为列表
然后到intarray
然后传播

What is a proper way to fill varargs? My attempt looks like a bycile at fist i construct range
then i convert it to list
then to intarray
then spread it

m.getColumns(*((count.. count + 35).toList().toIntArray()))

其中getColums是一种将colums索引作为varargs接受的方法

where getColums is a method which accepts colums indexes as varargs

推荐答案

是的,从这个意义上说,范围实际上离数组很远,很难将它们作为vararg参数传递.

Yeah, ranges are really far from arrays in this sense, it's rather hard to pass them in as vararg parameters.

您可以创建一个函数,将它们更快地转换为IntArray实例:

You could create a function to convert them to IntArray instances one step quicker:

fun IntRange.toIntArray() = this.toList().toIntArray()

m.getColumns(*(count..count + 35).toIntArray())

此转换的优化版本稍好:

A slightly better optimized version of this conversion:

fun IntRange.toIntArray(): IntArray {
    val size = this.last - this.first + 1
    var current = this.first
    return IntArray(size) { current++ }
}


或者您可以定义一个重载函数,该函数采用IntRange并进行转换以调用原始函数:


Or you could define an overloaded function that takes an IntRange and does the conversion to call the original:

fun getColumns(range: IntRange) = getColumns(*range.toList().toIntArray())

同样,这也可以利用上面的转换方法以获得更好的性能:

Again, this could also make use of the conversion method above for better performance:

fun getColumns(range: IntRange) = getColumns(*range.toIntArray())

这篇关于如何用范围填充可变参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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