When I'm trying to create the following code:
class SmartCast {
var array: MutableList<Int>? = null
fun processArray() {
if (array != null && !array.isEmpty()) {
// process
}
}
}
this error is shown:
Smart cast to 'MutableList' is impossible, because 'array' is a mutable property that could have been changed by this time
It's clear that the array
variable can be changed to null
in case of multi-threading. But if I use @Synchronized
annotation, there is no way to mutate the variable in between array != null
and !array.isEmpty()
.
@Synchronized
fun processArray() {
I'm wonder, why the compiler doesn't allow smart cast in synchronized blocks or maybe it's possible to specify somehow that my application is designed only for single-threaded mode?
UPDATE: According to the answers, I changed the code in the following way:
fun processArray() {
array?.takeUnless { it.isEmpty() }?.also {
for (elem in it)
// process elements
}
}