scala学习手记40 - case表达式里的模式变量和常量
2016-09-18 22:41
323 查看
再来看一下之前的一段代码:
在上面的代码里出现了三个占位符a, b和msg。他们就是占位符。
按照约定,Scala中模式变量要以小写字母开头,常量要以大写字母开头。所以这里一定要注意大小写,这里就是一个出错的实例:
虽然程序可以执行,但是在执行的时候会给出警告:
提示模式变量的模式无法匹配。执行结果也和预期严重不一致。执行的代码:
执行结果:
如果偏要使用这个值的话可以通过对象或类来引用这个变量:
此时的执行结果是正确的:
就这样!
######
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!!") } } }
虽然程序可以执行,但是在执行的时候会给出警告:
提示模式变量的模式无法匹配。执行结果也和预期严重不一致。执行的代码:
new Sample().process(100) new Sample().process(0) new Sample().process(10)
执行结果:
如果偏要使用这个值的话可以通过对象或类来引用这个变量:
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)
此时的执行结果是正确的:
就这样!
######
相关文章推荐
- 安卓开发第一讲---android的系统框架,dalvik虚拟机简介
- 第三周项目4-顺序表应用(2)
- JAVA基础--泛型的好处
- Java的数据库操作
- hdu 5868 2016 ACM/ICPC Asia Regional Dalian Online 1001 (burnside引理 polya定理)
- 【自学考试】数据结构导论总结
- RxJava使用(一)
- [LeetCode-Java]6. ZigZag Conversion
- Telerik自动化测试框架用后感一
- UVA 10089 Repackaging
- codeforces 712B. Memory and Trident
- 详解Android中AsyncTask的使用 from liuhe688
- 将树转化为二叉树表示
- 液晶显示知识总结
- Redis应用——使用Redis存储Session
- Mybatis,怀疑--使用--感悟
- VS 2012自动生成get 和set 方法
- 朴素贝叶斯
- 传感器
- HQL查询语言