2016-08-18 7 views
0

sound.idプロパティをnullableからnullnableに変換し、param of playメソッドとして渡すのに最適な方法は何ですか?null可能なプロパティにアクセスする方法はありますか?

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

チェック:http://stackoverflow.com/questions/34498562/in-kotlin-what-is-the-idiomatic-way-to-deal-with-nullable-values-referencing-o – piotrek1543

答えて

7

非nullになりますletが提供する引数を使用します。

sound.id?.let { 
    soundPool.play(it, 1F, 1F, 1, 0, 1F) 
} 

または

sound.id?.let { id -> 
    soundPool.play(id, 1F, 1F, 1, 0, 1F) 
} 
0

let{}はここソリューションです。

ちょうどこのようにそれを書く:

sound.id?.let { 
    soundPool.play(it, 1F, 1F, 1, 0, 1F) 
} 

--edit--

itはタイプInt(ないInt?)であり、ここで、引数である -

ていることに指摘してmfulton26 @感謝
+0

FYI:この例では、それは受取人*ではない。もしそうなら、 'it'の代わりに' this'を使う必要があります。 – mfulton26

関連する問題