sindrenm
01/13/2022, 4:17 PM(() -> Unit)?
doesn't always allow calling in the “natural” way. Is this a known issue? (Kotlin 1.6.0.)sindrenm
01/13/2022, 4:27 PMclass Runner(private val run: (() -> Unit)?) {
fun works() {
if (run == null) return
run.invoke()
}
fun fails() {
if (run == null) return
run()
}
}
sindrenm
01/13/2022, 4:28 PMfun runner(run: (() -> Unit)?) {
if (run == null) return
run()
}
sindrenm
01/13/2022, 4:30 PMDominaezzz
01/13/2022, 4:40 PMFleshgrinder
01/13/2022, 4:45 PMrun?.invoke() ?: return
Dominaezzz
01/13/2022, 4:57 PM?
in your workaround is not needed, which is part of the issue.Fleshgrinder
01/13/2022, 5:01 PMfun f() {
if (run == null) return
run() // requires smart cast, but doesn't work in any Kotlin version because of operator sugar
}
The alternative I gave for the particular example would be:
fun f() {
run?.invoke() ?: return
}
This would work in the example case, but not in the general case (obviously). A general solution to fix this:
fun f() {
// snip
run?.let { run ->
// snip
run()
// snip
}
// snip
}
Fleshgrinder
01/13/2022, 5:02 PMworks
function and the green background color of run
.Dominaezzz
01/13/2022, 5:02 PMworks
compile?Fleshgrinder
01/13/2022, 5:03 PMrun.invoke()
in works
gets transpiled to (run as () -> Unit).invoke()
. (Well, smart casted.)sindrenm
01/13/2022, 5:07 PMfun runner(run: (() -> Unit)?) {
if (run == null) return
run()
}
This is smart-cast + sugar, the only difference is we're dealing with a function parameter and not a class property:bashor
01/13/2022, 5:25 PMFleshgrinder
01/13/2022, 5:25 PML2
LINENUMBER 6 L2
ALOAD 0
GETFIELD Test.run : Lkotlin/jvm/functions/Function0;
INVOKEINTERFACE kotlin/jvm/functions/Function0.invoke ()Ljava/lang/Object; (itf)
POP
L3
LINENUMBER 7 L3
ALOAD 0
GETFIELD Test.run : Lkotlin/jvm/functions/Function0;
INVOKEINTERFACE kotlin/jvm/functions/Function0.invoke ()Ljava/lang/Object; (itf)
POP
L4
LINENUMBER 8 L4
ALOAD 1
INVOKEINTERFACE kotlin/jvm/functions/Function0.invoke ()Ljava/lang/Object; (itf)
POP
L5
LINENUMBER 9 L5
ALOAD 1
INVOKEINTERFACE kotlin/jvm/functions/Function0.invoke ()Ljava/lang/Object; (itf)
POP
Fleshgrinder
01/13/2022, 5:26 PMsindrenm
01/13/2022, 5:41 PM