Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 304 Vote(s) - 3.51 Average
  • 1
  • 2
  • 3
  • 4
  • 5
vararg parameter in a Kotlin lambda

#1
I'd like to define a function `f()` as follows (just an example) :

val f: (vararg strings: String) -> Unit = { for (str in it) println(str) }

so that I could invoke it with `f("a","b","c")`. For the above definition of `f()` I get the compilation error, pointing at the `vararg` modifier (Kotlin v. 1.3.60 ) :

Unsupported [modifier on parameter in function type]

How can I define a lambda that accepts a `vararg` parameter ?
Reply

#2
I'm afraid this is not possible. The following demonstrates the type of a function with `vararg`. A `vararg` parameter is represented by an `Array`:

fun withVarargs(vararg x: String) = Unit

val f: KFunction1<Array<out String>, Unit> = ::withVarargs

This behavior is also suggested in the [docs][1]:
> 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<out T>`.

So you had to use an `Array<String>` in your example. Instead of writing your function as a lambda, you may use an ordinary function that allows to use `vararg` and make the call look as desired:

fun f(vararg strings: String) = strings.forEach(::println)

f("a","b","c")


[1]:

[To see links please register here]

Reply

#3
If you need a function pointer (to be passed as an argument). It can be achieved with a workaround (hack):

fun f(vararg strings: String): Unit = strings.forEach(::println)


val fWrapper:(Array<String>)-> Unit = {arr:Array<String>->f(*arr)}
Reply

#4
Since vararg is not possible to be defined in functions signatures I'll go for this:

val f: (ArrayList<String>) -> Unit = { for (str in it) println(str) }
Reply

#5

```
inline infix <reified T, R : Any> fun foo(funcs: (vararg arg: T) -> R) = this.bar(funcs)
```

Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through