有没有更好的方法来访问可空属性?

时间:2016-08-18 17:59:43

标签: kotlin

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)
}

2 个答案:

答案 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指出