score:4

Accepted answer

you have a scope problem. m and n are not visible outside the pattern matching case.

this works:

object helloworld extends app {
  val a: any = 1
  val x = a match{
    case 2 => 22
    case m: string =>
      println(s"m = $m")
      "aa"
    case n: int =>
      println(s"n = $n")
      11
  }

  println(s"x = $x")
}

prints:

n = 1
x = 11

solution to the updated question::

object helloworld extends app {
  var m: any = ()
  var n: any = ()
  val a: any = 1
  val x = a match {
    case 2 => 22
    case m1: string =>
      m = m1
      "aa"
    case n1: int =>
      n = n1
      11
  }

  println(s"x = $x")
  println(s"m = $m n = $n")
}

prints:

x = 11
m = () n = 1

but this is not good scala style!

score:3

val m = ???
val n = ???
val x = a match {
  case 2 => 22           //if a is 2 x=22
  case m: string => "aa" //if a is a string create new variable m, x="aa"
  case n: int => 11      //if a is an int create new variable n, x=11
}
//if m or n were created forget them, now out of scope
//only original (unchanged) m and n variables are visible

score:4

this wording is sloppy:

if the case keyword is followed by a variable name, then the match expression is assigned to that variable

the case expression does not assign to an existing variable, it creates a new variable which is only available within the body of the case.

it should read:

if the case keyword is followed by a variable name, then a variable with that name is created and the matching value is assigned to that variable. the scope of the variable is the scope of the case body.


Related Query

More Query from same tag