Hi everybody, I have a stupid question about the k...
# test
h
Hi everybody, I have a stupid question about the kotlin test. How to assert a nullable object nonNull and make it type safe. I have tried to use
kotlin-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?
Copy code
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 !! 
  }
}
a
Use a val
Or assign it one
x
This happens because between the call to
assertNotNull(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:
Copy code
class MyTest{

  var result: XXX? = null

  fun test() {
    //...
    // saving data into db and got the result
    result?.let { result ->
      result.someProperty
    }
  }
}
👍 1