有没有更好的方法来访问可空属性?
将sound.id属性从可空或不可通过的方式转换为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) }
使用由let
提供的参数将是非空的:
sound.id?.let { soundPool.play(it, 1F, 1F, 1, 0, 1F) }
要么
sound.id?.let { id -> soundPool.play(id, 1F, 1F, 1, 0, 1F) }
let{}
是这里的解决方案。
只要这样写:
sound.id?.let { soundPool.play(it, 1F, 1F, 1, 0, 1F) }
– 编辑 –
it
是一个类型为Int
(不是Int?
)的参数 – 谢谢@ mfulton26指出了这一点