Home > Software engineering >  Decouple multiple variable let in Kotlin
Decouple multiple variable let in Kotlin

Time:04-06

I have a separate function that applies different gradient based on specified id, this function returns a compose Brush. When I call this function in my boxscore I have to wrap with let since it returns Brush?. This causes Android Studio to tell me the modifier must also be wrapped with the let keyword. How can I decouple this?

gradient function

fun appliedGradient(id: ScreenId): Brush? {
        return when (screen.id) {
            12 -> Brush.linearGradient(
                colors = listOf(Color.Transparent, Color.Red),
                start = Offset.Zero,
                end = Offset.Infinite
            )
            else -> Brush.linearGradient(
                colors = listOf(Color.Transparent, Color.Black),
                start = Offset.Zero,
                end = Offset.Infinite
        }
}

Function where applied gradient is called

@Composable
    fun GetContent(screenID: ScreenID): @Composable () -> Unit = {
        var size by remember { mutableStateOf(IntSize.Zero) }
        Box(modifier = Modifier
            .background(color = MaterialTheme.colors.surface))
        {
            //apply background image here
            appliedGradient(screenID)?.let {
                Modifier
                    .fillMaxSize().background(it)
            }?.let {
                LazyColumn(horizontalAlignment = Alignment.CenterHorizontally, modifier = it) {
                    //apply items
                }
            }
        }
    }

CodePudding user response:

I don't use Compose, so I'm not positive about this, but I would think you can move the contents of the second let block inside the first. When I have a let block with more than one line, I prefer to name the parameter for clarity instead of using implicit it.

@Composable
fun GetContent(screenID: ScreenID): @Composable () -> Unit = {
    var size by remember { mutableStateOf(IntSize.Zero) }
    Box(modifier = Modifier
        .background(color = MaterialTheme.colors.surface))
    {
        //apply background image here
        appliedGradient(screenID)?.let { gradient ->
            val modifier = Modifier.fillMaxSize().background(gradient)
            LazyColumn(horizontalAlignment = Alignment.CenterHorizontally, modifier = modifier) {
                //apply items
            }
        }
    }
}

CodePudding user response:

Simply change

fun appliedGradient(id: ScreenId): Brush? {

to

fun appliedGradient(id: ScreenId): Brush {

You declared it yourself as Brush? but since it never returns null that is not necessary

  • Related