Stanislav Verjikovskiy
Stanislav Verjikovskiy

Reputation: 343

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
}

Upvotes: 5

Views: 5242

Answers (2)

elm
elm

Reputation: 20405

Simple as well is this plain if-else expression,

def foo(value: Any) = if (value == "cond") None else Some(value)

A bit more elaborate is this,

def foo(value: Any) = Option(value).find( _ != "cond" )

which delivers None only if value equates "cond". Consider also using a for comprehension as follows,

def foo(value: Any) = for (v <- Option(value) if v != "cond") yield v

Upvotes: 5

mattinbits
mattinbits

Reputation: 10428

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.

Upvotes: 11

Related Questions