Something is bugging me regarding numeric rules during init and comparison

val longVar: Long = 0
val longVar: Long = 0L
val longVar = 0L

The above 3 all works are are the same.

However, comparison is much stricter.

if(longVar == 0)

The above fails. It must be written as if(longVar == 0L)

I don’t mind the strictness but I prefer the the var init phase to be AS strict and to disallow val longVar: Long = 0

Is it just me that feels the rules are not uniformally applied?

1 Like

It bugs not only you. Vote for https://youtrack.jetbrains.com/issue/KT-3936.

The lack of consistency is even worse than you describe as the other comparison operators (>, <, >=, <=) aren’t bothered about whether integer types match or not.

For example this compiles and runs fine:

fun main(args: Array<String>) {
    val a = 0L
    val b1 = (a >= 0)
    val b2 = (a >= 0L)
    println("b1 = $b1, b2 = $b2")
}

The problem was touched upon in this thread and is to do with the way the equals method works (essentially the types have to be exactly the same) whereas the compareTo method has overloads for comparing different integral types.

I don’t know what the best solution is to these problems, though allowing implicit widening conversions between the integral types was mentioned in that thread.

Wow. That’s wildly inconsistent. I did not expect (a >= 0) where a is long to compile.

I love kotlin but if these type of stuff doesn’t get fixed now while the language is still young, the baggage/resistance to not fix it will become bigger and bigger.

For me, I consider these type of inconsistencies major bugs in the language. When someone uses a language, they will naturally learn the rules/boundaries of what is allowed and what is not. If the boundaries are not enforced strictly, then the trust between the coder and the language is broken since any new rule he/she learns is worth much much less because the coder knows the language itself doesn’t care about about enforcing them.

1 Like

My ideal solution would be be to have a special “polymorphic” numeric literal type that can be automatically coerced to the right type if the value is in range. That would solve the problem for those cases, but it does complicate the type system somewhat.

1 Like