Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Scala return value itself for default pattern matching

For value: Any I need to check one string case.
For rest cases should return value itself.
What is the right syntax: case _ => _ ?

def foo(value: Any) = value match {
  case x: String => if (x == "cond") None else x
  case _ => _ // Compiler -> Not found value x$1. Unbound placeholder parameter
}
like image 607
Stanislav Verjikovskiy Avatar asked Dec 07 '22 23:12

Stanislav Verjikovskiy


1 Answers

Simply use some (arbitrary) identifier rather than _:

def foo(value: Any) = value match {
  case x: String => if (x == "cond") None else x
  case other => other
}

However, it is not best practice to return None in some cases, if you're not returning Some in the other cases. A more correct version would be:

def foo(value: Any) = value match {
  case "cond" => None
  case other => Some(other)
}

Then in either case you have an object of type Option.

like image 82
mattinbits Avatar answered May 11 '23 12:05

mattinbits