Scala return value from match case

12,501

In Scala, almost everything is an expression and returns a value, including pattern matches:

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
}
Share:
12,501
bajro
Author by

bajro

Updated on June 04, 2022

Comments

  • bajro
    bajro almost 2 years

    So here is my code:

    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
    }
    

    So the thing is my input is for example : "21m" and its fetching only the 21 and if its the regex matching with meters its assigning it to the val newValue and doing some stuff with it. But when I now want to print that value newValue it says that it cant find the value? How can I return this val outside from this match case?