parametersandroid-jetpack-composeparenthesesreadabilitycurly-braces

Is there any difference between using "content = { }" parameter or directly "{}" in Jetpack Compose?


I was wondering if it is better to use directly "content = {}" parameter instead of "{}" despite I see more often people using "{}".

Is the code cleaner or does the code load faster by using one or the other ? Is there any good practice ?

When using "{}"

@Composable
fun MyComposable(){
Box{}
}

When using "content = {}"

@Composable
fun MyComposable(){
Box(content = {})
}

Solution

  • The concepts used here are Kotlin trailing lambda and Kotlin named arguments.

    Kotlin named arguments

    So, this can be written with named arguments,

    @Composable
    fun MyComposable(){
        Box({})
    }
    

    like this

    @Composable
    fun MyComposable(){
        Box(content = {})
    }
    

    Kotlin trailing lambda

    From the docs,

    According to Kotlin convention, if the last parameter of a function is a function, then a lambda expression passed as the corresponding argument can be placed outside the parentheses

    This implies,

    @Composable
    fun MyComposable(){
        Box({})
    }
    

    and

    @Composable
    fun MyComposable(){
        Box() {}
    }
    

    are same.