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?
Using if expressions in case statements i match { case a if 0 to 9 contains a => println("0-9 range: " + a) case b if 10 to 19 contains b => println("10-19 range: " + a) case c if 20 to 29 contains c => println("20-29 range: " + a) case _ => println("Hmmm...") }
“match” is always defined in Scala's root class to make its availability to the all objects. This can contain a sequence of alternatives. Each alternative will start from case keyword. Each case statement includes a pattern and one or more expression which get evaluated if the specified pattern gets matched.
case _ => does not check for the type, so it would match anything (similar to default in Java). case _ : ByteType matches only an instance of ByteType . It is the same like case x : ByteType , just without binding the casted matched object to a name x .
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With