加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 为什么变量不能是一个稳定的标识符?

发布时间:2020-12-16 09:48:26 所属栏目:安全 来源:网络整理
导读:下列 def mMatch(s: String) = { var target: String = "a" s match { case `target` = println("It was " + target) case _ = println("It was something else") }} 不编译: error: stable identifier required,but target found. case target = println(
下列

def mMatch(s: String) = {
    var target: String = "a"
    s match {
        case `target` => println("It was " + target)
        case _ => println("It was something else")
    }
}

不编译:

error: stable identifier required,but target found.
case target => println(“It was ” + target)

为什么Scala要求val不是var。我想“因为”将是一个可以接受的答案,但我有感觉,有一个更深层的原因,我失踪。

解决方法

我怀疑,它是启用表切换优化的情况下,可能的情况下(没有成堆的检查,看看它是否有效)。例如,用代码

class Sw {
  def m(i: Int) = {
    val a = 3
    val b = 2
    val c = 1
    i match {
      case `a` => 0
      case `b` => -1
      case `c` => 4
      case _ => 2
    }
  }
}

你得到字节码

public int m(int);
  Code:
   0:   iconst_3
   1:   istore_2
   2:   iconst_2
   3:   istore_3
   4:   iconst_1
   5:   istore  4
   7:   iload_1
   8:   istore  5
   10:  iload   5
   12:  tableswitch{ //1 to 3
        1: 48;
        2: 44;
        3: 52;
        default: 40 }
   40:  iconst_2
   41:  goto    53
   44:  iconst_m1
   45:  goto    53
   48:  iconst_4
   49:  goto    53
   52:  iconst_0
   53:  ireturn

如果你使用vars(你必须检测他们是否改变,以知道表表达式是否仍然有效),这将是更复杂的。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读