gpt4 book ai didi

scala - 为什么 scala 不能将 Long switch 语句编译为 tableswitch

转载 作者:行者123 更新时间:2023-12-01 06:31:25 26 4
gpt4 key购买 nike

当我这样做的时候

val oldId :Long  = 123;

val i = 1
val newId = (oldId: @switch) match {
case 1 => 1234
case 2 => 5678
case 3 => 1122
case 4 => 3344
}

我收到编译器警告

[ant:scalac] mycode.scala:25: warning: could not emit switch for @switch annotated match
[ant:scalac] val newId = (oldId: @switch) match {
[ant:scalac] ^
[ant:scalac] one warning found

但是如果我使用以下代码

val oldId :Int  = 123;

val i = 1
val newId = (oldId: @switch) match {
case 1 => 1234
case 2 => 5678
case 3 => 1122
case 4 => 3344
}

然后编译器不会给我警告。为什么不能使用 Long 并获得 tableswitch

最佳答案

Why is it not possible to use a Long and get a tableswitch?

因为 JVM supports @tableswitch on int and types convertable to int :

The Java Virtual Machine's tableswitch and lookupswitch instructions operate only on int data. Because operations on byte, char, or short values are internally promoted to int, a switch whose expression evaluates to one of those types is compiled as though it evaluated to type int

因此,您会收到编译时警告,因为 long 不能隐式转换为 int

关于scala - 为什么 scala 不能将 Long switch 语句编译为 tableswitch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35975897/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com