I would like this to be possible :smile: It should...
# language-proposals
m
I would like this to be possible 😄 It should call
Foo.invoke()
rather than treating it as a trailing lambda since none is expected.
Copy code
fun main() {
    makeFoo() { // Too many arguments for public fun makeFoo(): Foo defined in root package in file main.kt
        42
    }
}

fun makeFoo() = Foo()

class Foo {
    operator fun invoke(arg: () -> Int) {
        println(arg())
    }
}
f
Doesn’t
(makeFoo()) {}
work? It’s typical for IIFE to require some additional parenthesis to work properly because otherwise it’s impossible to parse. 😛
It’s like the classic
if () {} if () {} else {}
problem.
m
It would work, but it doesn’t make a nice DSL 😅 Too bad that it’s hard to parse 😕
d
makeFoo()() { ... }
also works
m
Why the heck does that work 😂
Ah, I see
confusing 😄
d
If you want to make it a nice DSL you can do:
Copy code
val makeFoo get() = Foo()
Then
makeFoo { }
works
f
… and add
inline
too. 😉
m
@diesieben07 it’s a generic function unfortunately.
In my case
f
Funnel the lambda through.
m
Yeah that’s what I’m doing through extensions now. Repetitive but a solution.
f
Does your
invoke
actually require access to the innter state? Otherwise you could drop
makeFoo
and move the
invoke
to the companion.
m
Yeah it does. Basically similar to the Gradle Kotlin Script API 😮
f
Free standing construction functions mostly make sense in multi-platform projects where one wants to delegate the decision of how things are constructed from some
expect
to some
actual
. A
companion operator fun invoke
is almost always nicer in a JVM project. 😉
m
Functions have better auto completion imo
f
Extension functions in companions where bad so far but with the rest I don't see much of a difference. Free-standing functions are in general harder to find because it's not clear what belong to which class.
Or vice versa…
m
I keep getting autocompletion of companion invokes as
SomeClass.invoke(…)
or even
SomeClass.Companion.invoke(…)
f
Are you on the latest stable? EAP doesn’t have such issues.
m
Haven’t tested with .70 yet