有没有更好的方法来访问可空属性?
将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指出了这一点
- FragmentTransaction不会在Kotlin Android项目中编译
- java.lang.AbstractMethodError:用Mockito在Kotlin上运行espresso时的抽象方法
- 在房间中更改Flowable <List <Obj1 >>为Flowable <List <Obj2 >>
- 测试类中的java.util.logging.Logger
- Kotlin通用属性问题
- 如何使用Gradle在Kotlin上定位JVM 9?
- 我怎样才能使用回报,而不是让Kotlin?
- 为什么我不能让每一个Kotlin类都成为一个数据类?
- 匕首2.11 – 如何让Activity和Fragment共享共同的价值观?