6

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?

2
  • Just remove the assignment part val newValue = and the result of the pattern matching will be the returned value (if nothing after in your function). Commented Sep 2, 2015 at 12:50
  • okay I will try that solution too, thanks! Edit: It does not work! It is till taking the value from the input line... Commented Sep 2, 2015 at 12:52

1 Answer 1

17

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
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.