Thomas
05/03/2019, 2:40 PMoperator fun invoke
that takes a vararg
. Here's my stripped-down sample code, the trouble is with the syntax { fn }
in main
, it says "Too many arguments for public constructor NamesBuilder() defined in NamesBuilder". :
class NamesBuilder {
private val names:MutableList<String> = ArrayList()
fun build(): List<String> = names.toList()
operator fun invoke(vararg data: () -> String): NamesBuilder = this.apply { data.forEach { names.add(it()) } }
companion object Helper {
operator fun invoke(vararg data: () -> String): List<String> = NamesBuilder()(*data).build()
}
}
fun main() {
val fn: () -> String = { "1" }
println(NamesBuilder {fn}) // does not work -- Too many arguments...
println(NamesBuilder.invoke(fn)) // works fine, prints [1]
}
As I understand it, the { fn }
syntax should invoke the companion operator fun invoke function... and this works fine if I use .invoke(fn)
. I've tried numerous variations on this theme but no joy.
Can someone help me make this work?streetsofboston
05/03/2019, 2:45 PM(
and close )
for the last argument with a vararg lambda.
However, these work fine:
println(NamesBuilder({ fn() }))
println(NamesBuilder(fn))
thana
05/03/2019, 2:45 PM() -> () -> String
streetsofboston
05/03/2019, 2:48 PMNamesBuilder {fn}
is fixed to NamesBuilder {fn()}
, the error message is still shown. It seems to be an issue with omitting the round open and close brackets.
Not sure if this is a ‘bug’ or not for the compiler…thana
05/03/2019, 2:49 PMThomas
05/03/2019, 3:14 PMNamesBuilder({ fn() }))
syntax works. IntelliJ suggests that I pull the lambda out of the parentheses, so it seems like this ought to work.streetsofboston
05/03/2019, 3:15 PMCzar
05/03/2019, 3:39 PMkarelpeeters
05/03/2019, 4:19 PMkarelpeeters
05/03/2019, 4:21 PMThomas
05/03/2019, 6:05 PMfun baz(vararg a: () -> Unit) {
a.forEach { it() }
}
fun xy() { }
fun test() {
baz({xy()})
baz { xy() }
}
The first call to baz
works; the second fails with "Passing value as a vararg is only allowed inside a parenthesized argument list"
So that error seems to suggest the real limitation, and the compiler/IDE are providing a misleading error (Too many arguments...) and invalid hint to remove the parentheses.