Hi all, I've two infix functions `infix fun Any....
# announcements
p
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
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
Hi, yes it works but only for one variable and we need to use all the variables inside the fun1
j
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
Alternatively try to move the call to
fun2
inside the first block somehow, maybe look into something DSL like?
s
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
Thanks, fun2 inside fun1 can be a good solution for me