what should `println(4-2018.toString().length)` pr...
# announcements
a
what should
println(4-2018.toString().length)
print in your opinion?
r
0
d
0
m
But that is not a unary-minus anymore though.
Normal minus has a different precedence than unary minus: https://kotlinlang.org/docs/reference/grammar.html#precedence
spoiler alert, it prints
0
r
It seems normal for a method call to have priority over an operator call. unaryMinus is an operator, right?
j
And yes, I checked EXACTLY that on Ruby when it prints:
Copy code
puts 2018.to_s.length; # 4
puts -2018.to_s.length; # 5
puts 4-2018.to_s.length; # 0
x = 2018;
puts -x.to_s.length; # -4
I'd like to check other languages as well, but I don't know which ones allow to call methods on integer literals (java does not)
uhhh... unary minus is an operator when it's not a part of a number literal. same as the dot is a member access operator when it is not immediately followed by a digit
r
unaryMinus is always an operator in kotlin
e
Some languages do this exception (notably Java), others do not (like Kotlin) and prefer to keep simpler parsing rule. I’m not sure there is one right answer.
j
yes. I know, grammar says so
c
Consider the parser just looking at the following string:
-2018
. How should it parse it? Is the minus sign supposed to be part of the literal, or an operation on the lone number? There is no good way for the parser to make that choice and resolve the ambiguity, other than eliminating the possibility of using it as part of the literal, since it needs to recognize similar things as an operator in other contexts
e
It is possible (Java does it), but then
-
operator becomes this weird exception. Compare:
Copy code
4-2018.toString().length
4 - 2018.toString().length
- 2018.toString().length
-2018.toString().length
In Kotlin all of that is consistent in behavior. In Java…. it is not an issue, since you cannot do
4.toString()
and you cannot have extensions on
Int
in Java either. So it is logical for Java to do it the way Java does.