Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala error illegal variable in pattern alternative on pattern matching case

I am new to scala. I was writing a pattern matching as below:

  val capitals = Map("France" -> "Paris", "Japan" -> "Tokyo")
  show(capitals.get("test"))
  def show(x: Option[String]) = x match {
    case Some(s) | None  => s
  }

I am getting error:

Error: illegal variable in pattern alternative
    case Some(s) | None  => s
              ^

I am trying to see how can I achieve or condition like I have in if statement in java

if (str == null || str.isEmpty())

Can you help rewrite the code or point out the mistake?

Question: How do I mention or condition in a case pattern matching?

like image 484
happybayes Avatar asked Oct 21 '25 02:10

happybayes


2 Answers

This is how you pattern match on Options:

def show(x: Option[String]) = x match {
  case Some(s) => s
  case None => "N/A"
}

(by the way, you can also do something like this):

capitals.get("test").getOrElse("N/A")

Now, to add OR conditions to a pattern match case, you cannot use bound variables. This will work, however:

def show(x: Option[String]) = x match {
  case Some(_) | None => "a"
}

Note that the only difference is in Some(_) as opposed to your Some(s). Using Some(s) wouldn't make much sense because you can't reuse that s anyway (what if None comes, what would s be in that case?)

like image 84
slouc Avatar answered Oct 24 '25 03:10

slouc


I think this is what you are trying to achieve. If s has a value in the map return, s. If s has no value in the map, return a message indicating so.

val capitals = Map("France" -> "Paris", "Japan" -> "Tokyo")

def show(x: Option[String]) = x match {
  case Some(s)  => s
  case None     => "x has no value"
} 

show(capitals.get("mani"))

A similar and more concise version of show is capitals.get("mani").getOrElse("No value found") which returns No value found.

Further, you can use a guards to check various conditions on s such as if the first char is upper case. This first case will only match if s begins with an upper case character.

 def show(x: Option[String]) = x match {
     case Some(s) if(s.head.isUpper) => s
     case None     => "No value"
 } 
like image 39
Brian Avatar answered Oct 24 '25 02:10

Brian