Hi! I have a nullable `val property: String?` in `...
# announcements
d
Hi! I have a nullable
val property: String?
in
src/main
and then in
src/test
I have
if (property != null) property.length
and this gives an error that
property
cannot be smart-casted, because it's defined in a different module. But it's the same [gradle] module! Also I have just moved this class + its test from another module where there was no such error. Why can this happen? Drives me nuts. Tried to compile outside an IDE from console, same errors...
t
It looks like a known bug. You can find it here.
n
in the meantime you can always use
?.let {}
d
I've tried searching there for "smart cast" and didn't find anything similar...
But I wonder why it did work when same code was in different module. How can I match those settings (or whatever) in a new module... build.gradle.kts is identical, didn't help
t
Do you receive error in IDE or during compilation?
j
Is it really a bug? If I have this code:
Copy code
val property: String?
    get() = if (Random.nextInt(0, 100) < 50) null else "Its over 50"
then this:
if (property != null) property.length
might definitely throw null which might give issues with smartcasting
that is why I'd always would chose to use things like
property?.length
and not the good old fashioned java way of
if (something != null)
v
Are you sure it worked on the other module? That it does not work is expected to me. A module in the context of that error message or not a Gradle project. A module is the code that is compiled together in one compiler code. That's also the scope for
internal
. Tests are compiled separately from the production code. Smart casts have some restrictions, like they don't work with custom getters or delegation, as then on each call the result could be different. If the to be smart-casted property is in a different module (compilation unit), then the code where the property is could be changed to a custom getter but the code where the smart cast was done is not recompiled as the other module stays binary compatible.
d
@Vampire thanks!! I realized that in other module they were indeed with an
internal
modifier which I then removed! My clame "nothing changed" was wrong above 😞 I didn't know that
src/main
and
src/test
are considered different "modules".
v
There are simply too many "module"s out there 😄 Here is the module defined in that context: https://kotlinlang.org/docs/reference/visibility-modifiers.html#modules And indeed there is an exception for test source sets in Gradle that can see internal declarations in the production sources.
d
Oh, great thanks. That's a precise definition.