Please remind me about the following: If I declare...
# announcements
h
Please remind me about the following: If I declare a Long in my class, say
var f: Long = 5
, and in the course of my program, the value changes. And then I would like this check:
if (f == 10000) { ... }
. Why is it that it doesn't compile? Why do I need to supply an L to the hard-coded constant
10000
here? Shouldn't it be possible for the compiler to detect that
10000
is valid as a Long value?
s
It might be within range as a
Long
value, but it’ll still fail
.equals()
. I don’t know enough about numeric types on the JVM to really explain why, but I think this is an instance of the compiler disallowing a comparison to avoid subtle bugs
in the repl I tried a simple
5L.equals(5)
which evaluated to
false
I think there’s only a single
Long.equals(Any?)
defined, so it makes sense that the method would include a
other is Long
check
==
is supposed to resolve to an
equals()
call in Kotlin, but it wouldn’t be useful here and perhaps harmful to the developer to allow it. If implicit widening were allowed, you’d have Int values autoconverted to Long that suddenly wouldn’t be able to be compared to ints and it wouldn’t be obvious from the code why
h
Thanks.
i
It's a known issue, please vote for/follow the discussion in https://youtrack.jetbrains.com/issue/KT-3936