Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Kotlin 有没有更好的方法访问nullable属性?_Kotlin - Fatal编程技术网

Kotlin 有没有更好的方法访问nullable属性?

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.

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