Are nested composable declarations considered an a...
# compose
s
Are nested composable declarations considered an antipattern? What are the differences in these two apart from not having to pass all the variables in nested calls? Are there any performance differences?
Copy code
/// Approach 1: Nested declarations
@Composable
fun MyView1(currentNum: Int) {
    @Composable
    fun InnerView(num: Int) {
         Text(
              "$num",
              color = if (currentNum == num) Color.Red else Color.Black
         )
    }
    for (i in 0..currentNum) {
        InnerView(i)
    }
}

/// Approach 2: Normal top level declarations
@Composable
fun MyView2(currentNum: Int) {
    for (i in 0..currentNum) {
        InnerView(i, currentNum)
    }
}
@Composable
fun InnerView(num: Int, currentNum: Int) {
    Text(
        "$num",
        color = if (currentNum == num) Color.Red else Color.Black
    )
}
https://stackoverflow.com/questions/77940487/are-nested-composable-declarations-considered-as-an-antipattern
e
the first is effectively equivalent to
Copy code
@Composable
fun MyView1(currentNum: Int) {
    val innerView = @Composable { num: Int ->
         Text(
              "$num",
              color = if (currentNum == num) Color.Red else Color.Black
         )
    }
    for (i in 0..currentNum) {
        innerView(i)
    }
}
s
Right. So is there any difference regarding the skipability of the composable in either case? Any performance difference?
s
Local composable functions are never skippable (note that lambda /is/ skippable)
👍 1
v
Just as a curiosity, is there some internal restriction in the Kotlin compiler that makes it hard to implement generating skippable groups for local composable functions or is it just not implemented (yet)? And a follow-up question: do local normal functions get any memoization logic around them like lambdas do?
s
Local functions are a bit harder to transform, because they can capture things and aren't always transformed into objects like lambdas do, sometimes they are converted to a static method instead. I don't think there was any effort to generate skippable groups for them, same for memoization.
thank you color 3
s
Off to refactor my code 😅