I would like to know why my elapsed
variable ends up Long?
instead of Long
. I defined it as not nullable and none of the operations I execute on it could result in null.
Still get the error for the last line:
Operator call corresponds to a dot-qualified call 'elapsed.div(1000.toLong())' which is not allowed on a nullable receiver 'elapsed'.
var startTime: Long = 0
var _elapsedTime = MutableLiveData<Long>(0)
_elapsedTime.value = System.currentTimeMillis() - startTime
val elapsed = _elapsedTime.value
val testVal = elapsed / 1000.toLong()
It ends up as Long?
because the method LiveData.getValue()
is marked with @Nullable
in Java.
For the interoperability between Java and Kotlin, in Kotlin that method returns a nullable Long
, so Long?
.
https://kotlinlang.org/docs/reference/java-interop.html#nullability-annotations