https://kotlinlang.org logo
#announcements
Title
# announcements
p

PabloCasia

10/22/2019, 6:06 AM
Hi all, I've two infix functions
infix fun Any.fun1(block: () -> Unit) = block.invoke()
infix fun Any.fun2(block: () -> Unit) = block.invoke()
And I'm trying to use variables from first fun on second fun, something like:
fun1 { val item1 = "" } fun2 { val item2 = item1 }
But item1 scope is only fun1 Any suggestions? Aware from declare as a lateinit var outside the functions
j

jegul

10/22/2019, 6:45 AM
you can try something like this:
infix fun <T>Any.fun1(block: () -> T) = block.invoke()
infix fun <T>T.fun2(block: T.() -> Unit) = block.invoke(this)
so basically you are returning something from
fun1
and use it as receiver to
fun2
@PabloCasia
p

PabloCasia

10/22/2019, 7:40 AM
Hi, yes it works but only for one variable and we need to use all the variables inside the fun1
j

jegul

10/22/2019, 8:27 AM
I don’t think it’s possible to use it directly and I don’t actually understand what you are trying to achieve here, but you can workaround it by returning either
Pair
,
Triple
, or any other custom data class from
fun1
, and then use destructuring declarations on
fun2
.
k

karelpeeters

10/22/2019, 8:28 AM
Alternatively try to move the call to
fun2
inside the first block somehow, maybe look into something DSL like?
s

streetsofboston

10/22/2019, 11:20 AM
In your example, you can declare all your val/var outside the calls to fun1 and fun2. (Use so-called 'contracts' to be able to properly use `val`s, declaring that your `block`s are called exactly once).
p

PabloCasia

10/23/2019, 3:19 AM
Thanks, fun2 inside fun1 can be a good solution for me