Home > Software engineering >  In Scala how to access match case value in each case block
In Scala how to access match case value in each case block

Time:02-10

I want to access to the case value in the case block

 val a = "hello" 
  a match {
    case "hello" | "Hi" =>
      println("hello") // how can I access the right case value? Hello or Hi?
    case _ =>
      print("NA")
  }

CodePudding user response:

You can reference the matched value like so:

a match {
    case str @ ("hello" | "Hi") => println(str)
    case _ => print("NA")
}

CodePudding user response:

Another way could be -

a match {                                              
case str if str == "hello" | str == "Hi" => println(str)
case _ => println("NA")                                
}                                                      
  • Related