Style question. With @compose, there's lots of clo...
# compose
t
Style question. With @compose, there's lots of closures that get passed up and down the stack. Sometimes, I have the same closure that will get passed to two child calls, e.g.:
Copy code
@Composable
fun foo() {
   bar(onAnswer = { v -> v + 42 })
   baz(onAnswer = { v -> v + 42 })
)
Not wanting to repeat myself, I have tended to extract those cases, e.g.
Copy code
@Composable
fun foo() {
   val onAnswer:(Int) -> Int = { v -> v + 42 }
   bar(onAnswer)
   baz(onAnswer)
)
Having a long career in closure friendly languages, I'm cool with this. But Kotlin has the ability to do nested functions. Which are "new" to me. So they feel a little weird. I'm used to knowing that a fun lives at a predictable scope when I see that keyword. But I could rewrite the above as:
Copy code
@Composable
fun foo() {
   fun onAnswer(value:Int) = value + 42
   bar(::onAnswer)
   baz(::onAnswer)
)
What do others do? Is there any style/convention direction here? Are there subtle nuances to consider between a val closure and nested function?
e
the meaning of
return
is a bit different, otherwise a nested function is the same as a lambda
I typically only use it for disambiguation when returning a lambda from another block (to avoid
{ { ... } }
or when being able to specify the return type explicitly is useful
m
~Compose functions are designed to define the UI structure, not to handle business logic. This separation of concerns follows the principles of modern UI development, ensuring a clear division between the presentation layer and the business logic layer. A few reasons why:~ • Separating UI from logic makes your codebase cleaner and easier to maintain. Changes in the business logic won't require changes in the UI code and vice versa, reducing the risk of introducing bugs.Handling logic outside composable functions simplifies state management. It encourages the use of view models or similar patterns to manage state, which promotes a more consistent and predictable UI.Keeping composable functions focused solely on UI elements makes them more readable and understandable. It's clearer what each component does and how it fits into the overall UI structure. ~If you practice these methods, you create a more modular, flexible, and maintainable codebase. I’m not sure if you’re coding for Android, but I can link a few examples of their documentation that would probably make more sense. (Specifically the paradigm of using a screen view and content view composable.) Hope that helps!~ I misread the question… lol 😆
j
The Kotlin compiler implements nested functions using lambdas so there's little difference
t
Yeah, I noticed if you "inline" the nested function , any references to the ::func just get turned into a closure