误解scala'match'编译规则 [英] Misunderstanding of scala 'match' compile rules

查看:119
本文介绍了误解scala'match'编译规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须对Scala的match语义或编译器逻辑有一些基本的误解。此代码:

I must have some basic misunderstanding of the Scala 'match' semantics or the compiler logic. This code:

val stageStart:Int = 0
val stageShutDown:Int = Int.MaxValue
val stageErrorReport:Int = Int.MinValue

def stageString(stage:Int):String = stage match {
  case stageStart       => "Start"
  case stageShutDown    => "End"
  case stageErrorReport => "Error"
  case _                => "Step " + String.valueOf(stage)
}

会导致Unreachable Code错误在最后3'case'语句?如果不是用名称替换实际值(0,Int.MaxValue,Int.MinValue),它会编译 - 但现在我已经硬编码的值应该由他们的名字引用(因为所有通常的原因)。因为'val'永远不会改变,第一个版本是否也能工作?

results in "Unreachable Code" errors on the last 3 'case' statements? If instead of the names you substitute the actual values (0, Int.MaxValue, Int.MinValue) it compiles -- but now I've hard-coded values that should be referenced by their names (for all the usual reasons). Since a 'val' can never change, shouldn't the first version also work?

推荐答案

:如果 case 规则中的标识符以小写字母开头,则它们始终被视为变量。因此,第一个 case 总是匹配(存储 stage 到变量 stageStart ),其余3个不可达。您需要使用大写字母定义常量

There is a subtle yet important feature: If the identifier in case rules start with a lower-case letter, they're always treated as variables. So the first case matches always (storing stage into variable stageStart) and the rest 3 are unreachable. You need to define the constants with upper case letters as

val StageStart:Int = 0
val StageShutDown:Int = Int.MaxValue
val StageErrorReport:Int = Int.MinValue

def stageString(stage:Int):String = stage match {
  case StageStart       => "Start"
  case StageShutDown    => "End"
  case StageErrorReport => "Error"
  case _                => "Step " + String.valueOf(stage)
}

另请参见此模板匹配的常量。 answer Scala常量的命名约定?

这篇关于误解scala'match'编译规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆