设为首页 加入收藏

TOP

scala学习手记40 - case表达式里的模式变量和常量
2017-10-10 12:11:28 】 浏览:2218
Tags:scala 学习 手记 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!!")
    }
  }
}

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

image

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

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

执行结果:

image

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

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)

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

image

就这样!

######

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇scala学习手记39 - 模式匹配 下一篇scala学习手记40 - 使用case类

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目