为什么我的编译器要我在这里为 Map.forEach() 编写一个扩展函数?

问题描述

我启动了一个简单的 Android 应用来使用 Compose UI,并从 Google Developers 页面提取了一段关于如何显示带有粘性标题的列表的代码

我实现了代码和其他一些数据模型类,一切正常。它编译并构建,我看到我的撰写预览按预期工作。第二天回到我的电脑,打开 Android Studio,现在我在 grouped.forEach 函数内的 PlantList 语句中遇到编译时错误。 Android Studio 建议我为 Map.forEach() 创建一个扩展函数,但我不确定为什么我必须这样做。

Type mismatch.
required:
(Char,List<Plant>) → Unit
Found:
(Char) → Unit
Expected 2 parameters of types Char,List<Plant>
Destructuring declaration initializer of type Char must have a 'component2()' function

相关代码如下。让我难住的部分是前几天它在同一台计算机上运行,​​当我在那里签出代码时它仍然可以在我的另一台计算机上运行。我认为我的开发环境没有任何改变。

布局.kt:

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun PlantsList(grouped: Map<Char,List<Plant>>) {
    Column {
        TopAppBar(
            title = { Text("My Plant List") },)
        LazyColumn {
            grouped.forEach { (initial,plantsForInitial) ->
                stickyHeader {
                    CharacterHeader(initial)
                }

                items(plantsForInitial) { plant ->
                    PlantListItem(plant)
                }
            }
        }
    }
}

@Composable
fun PlantListItem(plant: Plant) {
    Row(verticalAlignment = Alignment.CenterVertically) {
        Image(painter = painterResource(plant.image),contentDescription = "An image of you plant",modifier = Modifier.width(75.dp)
        )
        Column {
            Text(plant.name)
            Text("time to next water")
        }
    }
}

@Composable
fun CharacterHeader(character: Char) {
    Column {
        Card(Modifier.fillMaxWidth().padding(8.dp),elevation = 8.dp) {
            Text(character.toString())
        }
    }
}

MainActivity.kt

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val orderedplantList = returnTempPlantList().groupBy { it.name[0] }
        setContent {
            PlantReminderTheme {
                // A surface container using the 'background' color from the theme
                Surface(color = MaterialTheme.colors.background) {
                    PlantsList(orderedplantList)
                }
            }
        }
    }
}

@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    val orderedplantList = returnTempPlantList().groupBy { it.name[0] }
    PlantReminderTheme {
        PlantsList(orderedplantList)
    }
}

Plant.kt:

data class Plant(
    var id: Int,var name: String,var image: Int
)

数据类PlantList(var Plants: List)

解决方法

只需从 lambda 中删除括号