angryziber / kotlin-puzzlers

A collection of Kotlin Puzzlers
419 stars 58 forks source link

NaN puzzler #64

Closed rpuxa closed 4 years ago

rpuxa commented 4 years ago
val number: Number = 0.0 / 0.0
println(if (number is Double) number == number else "number !is Double")

a) true b) false c) number !is Double d) None of the above

Correct answer: a. Compiler ignores smart cast to Double and compares numbers like Objects, i.e. using equals() method. And equals() method returns true if it compares two NaNs.

rpuxa commented 4 years ago

I ran this code in kotlin playground and it returned false, but in IntelliJ IDEA it returns true! WTF?

TWiStErRob commented 4 years ago

Playground uses 1.3.41 or 1.3.50, what's your project using? It could also be a NewInference bug?

rpuxa commented 4 years ago

I've tried on 1.3.50 and 1.3.60. Both versions print true.

TWiStErRob commented 4 years ago

So we need an option "it depends" 😮.

I also get true when pasting the two lines into kotlinc 1.3.50

rpuxa commented 4 years ago

By the way, one of the things I discovered - if you open Tools >> Kotlin >> Show Kotlin bytecode, it shows wrong bytecode. To figure out how code works i had to use external bytecode viewer.

rpuxa commented 4 years ago

And if you change platform to JS on playground it becomes to print true (╯°□°)╯︵ ┻━┻

TWiStErRob commented 4 years ago

(╯°□°)╯︵ ┻━┻

I think you just proved that it's a good puzzler!

angryziber commented 4 years ago

I put this into a kts file and it returns false, but yes, pasting to kotlinc returns true. Probably would need to find somebody to explain this @ KotlinConf :-)