https://kotlinlang.org logo
#compose
Title
# compose
t

Travis Griggs

10/04/2023, 10:26 PM
Weird. I have a naive forEach function on a "custom collection" like thing, that hides its internals:
Copy code
fun forEach(closure: (ValveSpan) -> Unit) {
   series.forEach(closure)
}
If I use this in a @Composable function and try to do a @Composition (Text) inside of the closure, the compose compiler won't do it (@Composable invocations can only happen from the context of a @Composable function). Using the stock forEach on normal collections is fine. Do I need to declare my custom forEach with some kind of annoation for compose to be happy using it?
👌 1
z

Zach Klippenstein (he/him) [MOD]

10/04/2023, 10:48 PM
You need to make your function inline
👆 1
This is the same reason you can call
suspend
functions from a
forEach
on eager collections in a suspending context
t

Travis Griggs

10/04/2023, 10:49 PM
i tried that. unfortunately, the whole reason I added that was that it's a private var it's enumerating, and inline and private vars do not mix apparently?
z

Zach Klippenstein (he/him) [MOD]

10/04/2023, 10:50 PM
inline
literally means it inlines the function body into the call site. So if the call site couldn’t access a private var, an inline function can’t
That’s also why it propagates the caller’s “color” – it’s not actually allocating a lambda for the parameter, just copying the function body into the caller.
One way to work around that is to make your private property
@PublishedApi internal
t

Travis Griggs

10/04/2023, 10:56 PM
thanks, that works
8 Views