Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ellipsis operator Java equivalence in Kotlin

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.

like image 807
Julian Torregrosa Avatar asked Nov 11 '17 03:11

Julian Torregrosa


People also ask

What means :: In Kotlin?

:: converts a Kotlin function into a lambda. this translates to MyClass(x, y) in Kotlin.

What is Vararg in Kotlin?

In Kotlin, You can pass a variable number of arguments to a function by declaring the function with a vararg parameter. a vararg parameter of type T is internally represented as an array of type T ( Array<T> ) inside the function body.

Does Kotlin have a spread operator?

It's Kotlin's spread operator — the operator that unpacks an array into the list of values from the array. It is needed when you want to pass an array as the vararg parameter. it will fail with Type mismatch: inferred type is Array<String> but String was expected compilation error.

How do you spread an array in Kotlin?

The * operator is known as the Spread Operator in Kotlin. When we call a vararg-function, we can pass arguments one-by-one, e.g. asList(1, 2, 3), or, if we already have an array and want to pass its contents to the function, we use the spread operator (prefix the array with *):


1 Answers

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() }
}
like image 54
Julian Torregrosa Avatar answered Oct 07 '22 08:10

Julian Torregrosa