Weird constant folding issue! Run this on JS: ```f...
# compiler
y
Weird constant folding issue! Run this on JS:
Copy code
fun main() {
    val x = 0.0
    println(1.0) // 1
    println(1.0.toString()) // 1
    println("${1.0}") // 1.0
    println(x) // 0
    println(x.toString()) // 0
    println("$x") // 0
}
Seems that
"${1.0}"
gets converted at compile time to
"1.0"
and not
"1"
which is what the normal behaviour is on JS
j
On which JS engine? I'm not sure you can rely on it to always be "1" everywhere.
y
Oooo that's fair, I'm seeing this on Chrome and Node, so V8 then. I'm not actually relying on it to be
1
, I was relying on it to be
1.0.toString()
which it surprisingly isn't, and because when put in a variable I get the non-
.0
result, I believe this is a weird constant folding bug
j
I don't think it's a strict bug, as other JS engines might render as 1.0 at runtime, too.
I think the runtime behavior is unspecified, and the compile-time behavior is specified (at least implicitly) to match the JVM Double.toString
y
That makes more sense okay! My issue with this is the inconsistency of behaviour with a very simple refactoring (putting a constant in a val), but perhaps this is a bigger issue about doubles to string on JS
j
Although https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString#description seems to imply when it's a while number the decimal part is always omitted
I would at least file a bug about it and see what JB people say
i
Hi! This is a known issue/design problem. Please note that the compiler of version "2.0.20-Beta2" show consistent result for your example. You can check it on playground. As it was noted, the compile time behaviour for Kotlin compiler is aligned with JVM rules. For example, the following code shows inconsistent results for Kotlin JS
Copy code
// Will be evaluated on compile time
const val a = 1.0.toString()

fun main() {
    println(a) // 1.0

    // Will be evaluated on runtime
    println(1.0.toString()) // 1
}
We tried to duplicate JS runtime behaviour, but there are problems. First, the specification is complicated. Second, the specification is not strict and the result can be different depending on JS engine (see KT-66922 for details). So for now we decided to live with different compile time and runtime result and come back to this problem later on (probably when we will start designing constant functions)