scala> class Sample { | | val max = 100 | val MIN = 0 | | def process(input: Int) { | input match { | case max => println("Don't try this") | case MIN => println("You matched min") | case _ => println("Unreachable!!") | } | } | } <console>:18: warning: patterns after a variable pattern cannot match (SLS 8.1.1) If you intended to match against value max in class Sample, you must use backticks, like: case `max` => case max => println("Don't try this") ^ <console>:19: warning: unreachable code due to variable pattern 'max' on line 18 case MIN => println("You matched min") ^ <console>:20: warning: unreachable code due to variable pattern 'max' on line 18 case _ => println("Unreachable!!") ^ <console>:19: warning: unreachable code case MIN => println("You matched min") ^ defined class Sample
警告信息提示因为错误的使用了模式值“max”,导致其后的匹配代码均不可达。看下执行结果:
1 2 3 4 5 6 7 8
scala> new Sample().process(100) Don't try this scala> new Sample().process(0) Don't try this