Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
来自匹配案例的Scala返回值_Scala_Scope_Pattern Matching_Return Value - Fatal编程技术网

来自匹配案例的Scala返回值

来自匹配案例的Scala返回值,scala,scope,pattern-matching,return-value,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.re

这是我的代码:

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
,并用它做一些事情。 但是当我现在想打印该值时,它说它找不到该值?
如何从这个匹配案例中在外部返回该val?

在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
}

只需删除赋值部分
val newValue=
,模式匹配的结果将是返回值(如果在函数中之后没有任何内容)。好的,我也将尝试该解决方案,谢谢!编辑:它不工作!直到从输入行获取值为止。。。