Ellipsis operator Java equivalence in Kotlin
Asked Answered
O

2

5

In Java, it is possible to do something like this: void function(Url... urls). It makes possible to use 1..n urls. The question is if it is possible to do the same thing with Kotlin.

Overtop answered 11/11, 2017 at 3:12 Comment(1)
kotlinlang.org/docs/reference/…Semanteme
L
5

From the Kotlin reference (https://kotlinlang.org/docs/reference/functions.html):

Variable number of arguments (Varargs)

A parameter of a function (normally the last one) may be marked with vararg modifier:

fun <T> asList(vararg ts: T): List<T> {
    val result = ArrayList<T>()
    for (t in ts) // ts is an Array
        result.add(t)
    return result
}

allowing a variable number of arguments to be passed to the function:

val list = asList(1, 2, 3)

Inside a function a vararg-parameter of type T is visible as an array of T, i.e. the ts variable in the example above has type Array.

Beware of a difference with Java: in Java you can pass an array as single parameter, while in Kotlin you must explicitly unpack the array, so that every array element becomes a separate argument. But you can do it by simply putting the * character before the corresponding argument:

fun main(args: Array<String>) {
    val list = listOf("args: ", *args)
    println(list)
}

(See how it lets you combine the values from an array and some fixed values in a single call, which is not allowed in Java).

Liam answered 11/11, 2017 at 21:3 Comment(0)
O
7

The solution is with vararg and the it is possible to iterate over the parameter.

private fun areValidFields(vararg fields: String) : Boolean{
    return fields.none { it.isNullOrEmpty() || it.isBlank() }
}
Overtop answered 11/11, 2017 at 3:33 Comment(0)
L
5

From the Kotlin reference (https://kotlinlang.org/docs/reference/functions.html):

Variable number of arguments (Varargs)

A parameter of a function (normally the last one) may be marked with vararg modifier:

fun <T> asList(vararg ts: T): List<T> {
    val result = ArrayList<T>()
    for (t in ts) // ts is an Array
        result.add(t)
    return result
}

allowing a variable number of arguments to be passed to the function:

val list = asList(1, 2, 3)

Inside a function a vararg-parameter of type T is visible as an array of T, i.e. the ts variable in the example above has type Array.

Beware of a difference with Java: in Java you can pass an array as single parameter, while in Kotlin you must explicitly unpack the array, so that every array element becomes a separate argument. But you can do it by simply putting the * character before the corresponding argument:

fun main(args: Array<String>) {
    val list = listOf("args: ", *args)
    println(list)
}

(See how it lets you combine the values from an array and some fixed values in a single call, which is not allowed in Java).

Liam answered 11/11, 2017 at 21:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.