https://kotlinlang.org logo
Title
d

Dominaezzz

08/15/2019, 10:12 PM
Is there a contract to let Kotlin know that my member `val`'s value will stay the same? Basically I need smart casting to work on
thing
in
data class Wrapper(val thing: String?)
(from another module of course).
3
m

marstran

08/16/2019, 7:27 AM
It will work as long as the property doesn't have a custom getter, or is delegated.
d

diesieben07

08/16/2019, 7:42 AM
From another module? I don't think so.
m

marstran

08/16/2019, 7:49 AM
Why would it work differently from another module @diesieben07?
d

diesieben07

08/16/2019, 7:50 AM
Because of separate compilation. Someone might compile something with your module and your property is in a data-class. You then switch that property to be a computed one (custom getter), which means the smart-cast would no longer be allowed, but the other module is already compiled with the smart-cast in place.
From the docs:
val properties - if the property is private or internal or the check is performed in the same module where the property is declared. Smart casts aren't applicable to open properties or properties that have custom getters
m

marstran

08/16/2019, 8:01 AM
Seems a bit weird to me. It wouldn't be any different than, let's say, removing a function, right? If the other module was already compiled with a call to that function, it would throw a
NoSuchMethodError
. In this case, I think it would throw an NPE because of the null-check the compiler inserts when it smart casts.
So, changing the property to a custom getter or delegate would just be a breaking change.
But that might just be what that rule avoids though.
d

diesieben07

08/16/2019, 8:02 AM
So, changing the property to a custom getter or delegate would just be a breaking change.
Yes, this is a tradeoff. The Kotlin creators chose to make this not a breaking change
Its like changing a function implementation
m

marstran

08/16/2019, 8:02 AM
Right 👍