English 中文(简体)
a. “整体”的范围。 MIN_VALUE.UByte.import_VALUE”不符合预期。
原标题:range of "UByte.MIN_VALUE..UByte.MAX_VALUE" is not in line with expectations
  • 时间:2024-04-13 14:13:25
  •  标签:
  • kotlin

我试图从0到255年,即未签署文书的范围,这是我的法典。

for (b in UByte.MIN_VALUE..UByte.MAX_VALUE) {
    // do something with b
}

但是,为什么它从0到2^32-1,即没有签名的形形状?

是否有隐藏的自动转换类型?

我试图抹去这一范围的规模,即法典:

val range = UByte.MIN_VALUE..UByte.MAX_VALUE
println(range.toList().size)

产出“256”

它不符合统一法

问题回答

我认为,你刚刚找到了汇编者。

通常为。 与此类似,汇编者将产生从<代码>tRange到<>的代码,并生成<代码>while (iterator.hasNext()。

但是,在研究生成的JVictor bytecode(不能在Kotlin/JS上照搬这种行为),似乎汇编者试图将这种行为变成类似于以下Java(pseudo)编码的C类循环:

for (UInt b = UByte.MIN_VALUE ; b <= UByte.MAX_VALUE ; b++) {
    // ...
}

但是,它没有做<条码>b和lt;=UByte. . Fair_VALUE,而是生成了<条码>b <= UInt. . . . . 下面是特稿的样本:

 5: iconst_0
 6: istore_1
 7: iload_1
 8: iconst_m1
 9: invokestatic  #18                 // Method kotlin/UnsignedKt.uintCompare:(II)I
12: ifgt          28
15: iload_1
16: istore_2
17: iload_2
18: iconst_m1
19: if_icmpeq     28
22: iinc          1, 1
25: goto          15
28: return

Notice the iconst_m1, this pushes -1 as an int (which is the max value of an unsigned int).


To achieve the correct result, you can assign the range expression to some local val first, so the compiler does not do this optimisation (though this is not technically guaranteed).

这显然违反了Kotlin规格的“for, loop应当做些什么。 根据spec,for 住宿相当于:

when(val iter = (UByte.MIN_VALUE..UByte.MAX_VALUE).iterator()) {
    else -> while (iter.hasNext()) {
        val b = iter.next()
        // loop body goes here...
    }
}

But this only loops from 0 to 255, which is correct.





相关问题
Exposed runs query on all HikariCP open connections

I m running a Ktor server with a PostgreSQL database and just set up the JetBrains Exposed ORM framework with HikariCP for connection pooling (per the recommendation in the Ktor documentation). My ...

SQLite Kotlin issue - no database

I am trying to create boardgamegeek APIs based app in AndroidStudio, however from unknown reason I m getting my database created with no columns. Here s Logical log: (1) no such table: games in "...

Flutter App cannot be installed on Android TV

I m building a Flutter app that should support Android TV and Mobile devices. Despite Google Play shows that it is supported, I cannot install app on my MiBox device. While trying to install it, both ...

热门标签