0

What is the best way to convert sound.id property from nullable to nonnulable and pass it as param of play method?

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)
}
Igor
  • 2,039
  • 23
  • 27
  • 1
    check: http://stackoverflow.com/questions/34498562/in-kotlin-what-is-the-idiomatic-way-to-deal-with-nullable-values-referencing-o – piotrek1543 Aug 18 '16 at 20:33

2 Answers2

7

Use the argument provided by let which will be non-null:

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

or

sound.id?.let { id ->
    soundPool.play(id, 1F, 1F, 1, 0, 1F)
}
mfulton26
  • 29,956
  • 6
  • 64
  • 88
0

let{} is the solution here.

Just write it like this:

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

--edit--

it is an argument here that is of type Int (not Int?) - thanks @mfulton26 for pointing that out

rafal
  • 3,120
  • 1
  • 17
  • 12
  • FYI: In this example, `it` is not a *receiver*. If it were then you would need to use `this` instead of `it`. – mfulton26 Aug 18 '16 at 18:36