scala学习手记40 - case表达式里的模式变量和常量

时间:2023-03-09 16:57:45
scala学习手记40 - case表达式里的模式变量和常量

再来看一下之前的一段代码:

def process(input: Any) {
input match {
case (a: Int, b: Int) => println("Processing (int, int)... ")
case (a: Double, b: Double) => println("Processing (double, double)... ")
case msg: Int if (msg > 1000000) => println("Processing int > 1000000")
case msg: Int => println("Processing int... ")
case msg: String => println("Processing string... ")
case _ => printf("Can't handle %s... ", input)
}
}

在上面的代码里出现了三个占位符a, b和msg。他们就是占位符。

按照约定,Scala中模式变量要以小写字母开头,常量要以大写字母开头。所以这里一定要注意大小写,这里就是一个出错的实例:

class Sample {
val max = 100
val MIN = 0
def process(input: Int) {
input match {
case max => println("Don't try this at home")
case MIN => println("You matched min")
case _ => println("Unreachable!!")
}
}
}

虽然程序可以执行,但是在执行的时候会给出警告:

scala学习手记40 - case表达式里的模式变量和常量

提示模式变量的模式无法匹配。执行结果也和预期严重不一致。执行的代码:

new Sample().process(100)
new Sample().process(0)
new Sample().process(10)

执行结果:

scala学习手记40 - case表达式里的模式变量和常量

如果偏要使用这个值的话可以通过对象或类来引用这个变量:

class Sample {
val max = 100
val MIN = 0
def process(input: Int) {
input match {
case this.max => println("Don't try this at home")
case MIN => println("You matched min")
case _ => println("Unreachable!!")
}
}
} new Sample().process(100)
new Sample().process(0)
new Sample().process(10)

此时的执行结果是正确的:

scala学习手记40 - case表达式里的模式变量和常量

就这样!

######