I have a data class with some nullable `val` prope...
# general-advice
z
I have a data class with some nullable
val
properties. It's defined in a
core
module. I'm using it in a
web
module. Sometimes it can be smart-cast to its non-nullable version, but other times it can't. I thought that if I wrap usage in an
if (nullableProp != null) { doSomethingWith(nullableProp.toString()) }
, it would be safe, but it's not. Browsing for answers points to cases where it's a
var
, which could be reassigned between dereferencing calls. Or, the other module can be recompiled(?) and not be nullable anymore. But surely, a simple data class with `val`s is safe, right? I was able to swap a `forEach`'s
it
with the deconstructed props, and it works fine then, so it seems like it's related to dereferencing it more than once, since deconstructing (having a single variable for the property) can smart cast, even though it's still a Public API in a different module
Oh, I guess you could have a data class with a nullable property that flip flops values in the same instance, right? Like
Copy code
data class Something(val somethingStatic: String) {
    val flipFlop: String?
        get() =
            if (randomInt().even) { somethingStatic }
            else { null }
}
Is that why?
c
Yes, it's one of the cases
The main solution is simply to create a local variable, replace
Copy code
if (foo.nulableProp != null) {
    doSomethingWith(foo.nullableProp)
}
by
Copy code
val nullableProp = foo.nullableProp
if (nullableProp != null) {
    doSomethingWith(nullableProp)
}
This way, the smart-cast works
Another case that breaks this is if in a future version you change the
val
to a
var
, it's also not safe to smart-cast anymore