Scala从匹配大小写

时间:2015-09-02 12:47:20

标签: scala scope pattern-matching return-value

所以这是我的代码:

val regexMeter = """^\s*(\d+,*\d+)\s*[m]\s*$""".r
val regexCentimeter = """^\s*(\d+,*\d+)\s*cm\s*$""".r
val regexDecimeter = """^\s*(\d+,*\d+)\s*dm\s*$""".r
val regexMillimeter = """^\s*(\d+,*\d+)\s*mm\s*$""".r

val height = scala.io.StdIn.readLine("Please insert the height of your shape:")
height match {
  case regexMeter(value) => val newValue = value.toDouble*100
  case regexCentimeter(value) => val newValue = value.toDouble
  case regexDecimeter(value) => val newValue = value.toDouble*10
  case regexMillimeter(value) => val newValue = value.toDouble/10
  case _ => throw new IllegalArgumentException
}

所以我的输入是例如:" 21m"并且它只获取21并且如果它的正则表达式与米匹配,它将它分配给val newValue并用它做一些事情。 但是,当我现在想要打印那个值newValue时,它说它无法找到价值? 如何从这个匹配案例中返回此val?

1 个答案:

答案 0 :(得分:14)

在Scala中,几乎所有东西都是表达式并返回一个值,包括模式匹配:

val newValue = height match {
    case regexMeter(value) => value.toDouble*100
    case regexCentimeter(value) => value.toDouble
    case regexDecimeter(value) => value.toDouble*10
    case regexMillimeter(value) => value.toDouble/10
    case _ => throw new IllegalArgumentException
}