You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

跨模块公共API属性无法智能转换为Property,求最优解决方案

问题解决

最优方案

直接使用also块中接收的非空参数it传递给updateProperty,修改后的代码如下:

fun onMessage(message: Message) {
    message.property?.also {
        repository.updateProperty(it)
    }
}

原因说明

编译器报错是因为message.property是跨模块的公开API属性,编译器无法确保在?.also的安全调用之后,到你再次访问message.property的这段时间里,该属性不会被其他线程或外部代码修改为null,因此无法进行智能转换。而also块里的it是安全调用后已经确认非空的实例,直接使用它就能避免这个问题。

另外还有两种备选方案,但都不如上面的简洁:

  • 使用let函数:
fun onMessage(message: Message) {
    message.property?.let { property ->
        repository.updateProperty(property)
    }
}
  • 先将属性赋值给临时变量:
fun onMessage(message: Message) {
    val property = message.property
    property?.also {
        repository.updateProperty(property)
    }
}

内容的提问来源于stack exchange,提问作者Daniel Wallman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 04:19:54