将 sound.id 属性从nullable转换为nonnulable并将其作为play方法传递的最佳方法是什么?
class Sound() {
var id: Int? = null
}
val sound = Sound()
...
//smarcat imposible becouse 'sound.id' is mutable property that
//could have changed by this time
if(sound.id != null)
soundPool.play(sound.id, 1F, 1F, 1, 0, 1F)
//smarcat imposible becouse 'sound.id' is mutable property that
//could have changed by this time
sound.id?.let {
soundPool.play(sound.id, 1F, 1F, 1, 0, 1F)
}
答案 0 :(得分:7)
使用let
提供的非空的参数:
sound.id?.let {
soundPool.play(it, 1F, 1F, 1, 0, 1F)
}
或
sound.id?.let { id ->
soundPool.play(id, 1F, 1F, 1, 0, 1F)
}
答案 1 :(得分:0)
let{}
就是这里的解决方案。
就这样写:
sound.id?.let {
soundPool.play(it, 1F, 1F, 1, 0, 1F)
}
- 编辑 -
it
这里的参数类型为Int
(不是Int?
) - 感谢@ mfulton26指出