'Decouple multiple variable let in Kotlin
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
)
14 -> Brush.linearGradient(
colors = listOf(Color.Transparent, Color.BLUE),
start = Offset.Zero,
end = Offset.Infinite
)
else -> null
}
}
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
}
}
}
}
Solution 1:[1]
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
}
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tenfour04 |
