Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill varargs with range?

Tags:

kotlin

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

where getColums is a method which accepts colums indexes as varargs

like image 455
Yarh Avatar asked May 22 '18 16:05

Yarh


2 Answers

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


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++ }
}

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())
like image 75
zsmb13 Avatar answered Sep 28 '22 08:09

zsmb13


You call varargs method with either a number of comma separated variables or with an array.

Unfortunately, there is no shortcut to making array from a range.

But, you can create an array directly:

m.getColumns(*IntArray(35) { count + it })
like image 32
TpoM6oH Avatar answered Sep 28 '22 06:09

TpoM6oH