Kotlin 有没有更好的方法访问nullable属性?
将sound.id属性从可空转换为不可空并将其作为播放方法的参数传递的最佳方法是什么Kotlin 有没有更好的方法访问nullable属性?,kotlin,Kotlin,将sound.id属性从可空转换为不可空并将其作为播放方法的参数传递的最佳方法是什么 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.
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)
}
使用提供的参数,该参数将不为null:
sound.id?.let {
soundPool.play(it, 1F, 1F, 1, 0, 1F)
}
或
let{}
是这里的解决方案
就这样写吧:
sound.id?.let {
soundPool.play(it, 1F, 1F, 1, 0, 1F)
}
--编辑--
it
是一个类型为Int
(不是Int?
)的参数-感谢@mfulton26指出FYI:在本例中,it
不是接收器。如果是,则需要使用this
而不是it
。检查:
sound.id?.let {
soundPool.play(it, 1F, 1F, 1, 0, 1F)
}