【问题标题】:Why can't scala compile a Long switch statement to a tableswitch为什么 scala 不能将 Long switch 语句编译为 tableswitch
【发布时间】:2016-03-14 05:51:45
【问题描述】:

当我这样做时

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

【问题讨论】:

  • 自然的问题是为什么编译器不报告原因。该文档确实警告说没有针对两种情况发出警告。

标签: scala switch-statement


【解决方案1】:

为什么不能使用 Long 并获得 tableswitch?

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

Java 虚拟机的 tableswitch 和 lookupswitch 指令仅对 int 数据进行操作。因为对 byte、char 或 short 值的操作在内部被提升为 int,所以表达式计算为这些类型之一的 switch 被编译为好像它计算为 int 类型一样

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

【讨论】:

  • 嗯,你知道为什么会这样吗?我猜想与使用 32 位处理器有效地实现操作并希望保持向后能力有关。也许?
  • @CarlosBribiescas 这是因为Java 根本不支持long 在switch case 中。开关值必须是bytecharshort(都可以转换为int)或string(在java 7 中添加并具有special case of a tableswitch),因为开关语句将被转换到 tableswitches 或 lookuptables,它们仅在字节码级别支持 int
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-04
  • 1970-01-01
  • 2022-01-07
  • 2021-11-24
  • 1970-01-01
相关资源
最近更新 更多