I face a confuse problem during learning Kotlin on...
# announcements
c
I face a confuse problem during learning Kotlin on hyperskill: https://hyperskill.org/learn/step/10784, here is there detail:
Copy code
//Consider the code snippet below. What will it print?

var num = 0
println(num++ + ++num)
Here is my step
Copy code
num++ + ++num     (num = 0)
num++ + 1         (num = 1)
1 + 1             (num = 1)
Am i correct?
FYI Order of precedences: 1. Parentheses; 2. Postfix increment/decrement; 3. Unary plus/minus, prefix increment/decrement; 4. Multiplication, division, and modulus; 5. Addition and subtraction; 6. Assignment operations.
j
Dont worry if you don't know. My suggestion is just run it and see. It's a terrible question really, and an example of confusing code that should never exist in a real codebase. Why? Its too hard to see what it does! Good software doesn't rely on mental gymnastics and humans parsing code.
☝️ 3
💡 3
t
It doesn't really matter which side is resolved first in this case. The answer is
2
either way. It's either
1 + 1
or
0 + 2
and after execution, the value of
num
will also be
2
in both cases.
💡 1
👌 2
Of course things like this might happen in other circumstances, but incrementing a variable twice in two different ways in a single expression seems like a very unusual case and I'd agree with @virtualrainbow that confusing code like that should be avoided. Anyway, there is always the really important step: Write a test that checks the behaviour of your code. Readable and understandable code is important, but not as important as code that actually achieves what you're trying to do.
2
c
Thanks for your info, I still love this example for learning new language except that make me feel a little bit uncomfortable due to don't know what actually do under the hood 😞
n
I've been using Kotlin since 1.0.x and even I'm not sure. it's not the kind of thing that one would write, nor would it get past code review. agree with everything said so far, but especially
Write a test that checks the behaviour of your code.
1