hantsy
04/22/2024, 2:55 AMkotlin-test
assertNotNull
to assert an object non null, but finally in the following codes, I still have to use !!
to convert it to non null value, if possible use some assert to convert it non null safely?
class MyTest{
var result: XXX? = null
fun test() {
//...
// saving data into db and got the result
assertNotNull(result)
result.someProperty // if possible use this directly, with type cast to none null using !!
}
}
agrosner
04/22/2024, 10:42 AMagrosner
04/22/2024, 10:42 AMxoangon
04/23/2024, 6:39 AMassertNotNull(result)
and result.someProperty
, the value of result
could be modified from another thread.
You can use an scope function like let
, that will guarantee that the value hasn't been mutated in that scope:
class MyTest{
var result: XXX? = null
fun test() {
//...
// saving data into db and got the result
result?.let { result ->
result.someProperty
}
}
}