nussafe在kotlin中如何繁殖?
考虑代码示例:
val contentLength :Long? = 1 val float = contentLength?.toFloat() val any = (float ?: 0) * 1.25 // ^ // compilation error here
如果我尝试像这样提取变量:
val casted = (float ?: 0)
IDE显示casted
有Any
类型。 为什么会发生? 如何从float引用获取nullsafe浮点值并将其乘以另一个浮点值?
更新
用0.0
代替0
:
(float ?: 0.0)
没有效果。 🙁
改变线
val any = (float ?: 0.0) * 1.25
至
val any = (float ?: 0.0f) * 1.25f
否则你把double
和float
混合导致编译错误