带注释的可空类型的条件值声明引发 'type inference failed'

Conditional value declaration of annotated nullable type throws 'type inference failed'

我想有条件地声明类型 @Composable (() -> Unit)? 的值,如下所示:

val myComposable: @Composable (() -> Unit)? = { /* something */ }.takeIf { condition }

原因是因为我想使用 Compose 的 ListItemsecondaryText 参数:

// Jetpack compose component
@Composable
fun ListItem(
  secondaryText: @Composable (() -> Unit)? = null,
  // ...
)
// My Usage
ListItem(
  secondaryText = { /* something */ }.takeIf { condition == true }
)

但事实证明这样做会引发以下错误:

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

后来我实现了这段代码编译:

val secondaryText: @Composable (() -> Unit)? = if (condition) {
  null
} else {
  { /* something */ }
}

这两个声明有什么区别,为什么前者会导致类型推断失败?

当您执行 { /* something */ } 时,您创建了一个类型为 () -> Unit 的值。添加 .takeIf { condition } 会将类型更改为 (() -> Unit)?。没有信息表明这是 @Composable.

这就是您的第二种方法起作用的原因:您已指定要创建 @Composable

您可以通过明确声明您正在使用 @Composable:

来解决这个问题
ListItem(
    secondaryText = (@Composable { /* something */ }).takeIf { condition }
)