Android Compose - Map string to composable items error

Viewed 53

I'm trying to map string to composable items, simply like this:

package com.example.application.component

import androidx.compose.material.Text
import androidx.compose.runtime.Composable

@Composable
fun C1(str: String) {
    Text(text = str)
}

@Composable
fun C2(str: String) {
    Text(text = str)
}

@Composable
fun C3(str: String) {
    Text(text = str)
}

@Composable
fun CAll() {
    val map: Map<String, @Composable (String) -> Unit> = mapOf(
        "c1" to { C1(str = it) }, // ok
        "c2" to { C2(str = it) }, // error
        "c3" to { C3(str = it) }, // error
    )
    // other codes
}

But unfortunately, Android Studio starts reporting errors from the second mapped item:

Type inference failed. Expected type mismatch: inferred type is @Composable (String) -> Unit but (String) -> Unit was expected

However, I can successfully build and run the code without any errors and warnings.

I guess I can ignore the errors, but the red squiggly lines in the project are really annoying. Is this a bug in Android Studio, or should I use another way of writing it?

1 Answers

That is a studio bug. Jetpack Compose is relatively new, so it might not have worked its way around the annotation in this particular context. Please file a report at the issue tracker, and link there. There's no problem with the code, and it's confirmed by the fact that you are indeed getting the desired behaviour.

Related