https://kotlinlang.org logo
Title
j

Jakub Gwóźdź

10/12/2018, 2:09 PM
one of the puzzlers from kotlinconf surprised me. why the unary
-
is not part of the number literal?
fun main(args: Array<String>) {
    println(-2018.toString().length)
}
prints -4, because method call has higher priority than unaryMinus. I mean, I understand the reasoning for operators precedence and indeed it makes perfect sense to call the method before making any other operations. But in case of literals it would make much more sense to glue the minus char with the digits. Similarly as the dot between digits is not treated as a method call.
m

marstran

10/12/2018, 2:16 PM
Behaving differently because it is a literal could lead to some other weird behaviour. For example, you expect these two examples to print the same result:
println(-2018.toString().length)
and
val num = 2018
println(-num.toString().length)
c

Casey Brooks

10/12/2018, 2:22 PM
Also consider the fact that a
-
has two possible meanings within the context of numbers: indicating a negative number, or effectively subtracting a number from 0. While the result is the same, the semantics behind it ar different (one is part of the number, the other is an operation on the number). For the sake of an unambiguous grammar, a single one has to be chosen, and it makes more sense to take the
-
as an operation, so that it doesn’t need to handle negative numbers and negative variables differently
m

marstran

10/12/2018, 2:22 PM
All prefix operators has the same precedence, including
!
. Normal behaviour for
!
in a chain of method calls ending in a boolean is
!(obj.returnsBoolean())
, not
(!obj).returnBoolean()
.