Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A More Powerful getOrElse?

Tags:

scala

I have the following code:

val userName = users.get(userID) match {
  case Some(user) => user.name
  case None => "Invalid User ID"
}

Is there a more concise way of writing this?

I was wondering if there was something similar to getOrElse that would let me apply a function if it is successful (to extract the user name), or return a plain value otherwise.

like image 388
Eduardo Avatar asked May 17 '26 01:05

Eduardo


1 Answers

scala> Map("a" -> 1).get("a").fold("invalid user id")("value:"+_)
res15: String = value:1

scala> Map("a" -> 1).get("b").fold("invalid user id")("value:"+_)
res16: String = invalid user id

Option.fold has some problems with type inference, for potential pitfalls see another answer.

like image 99
kiritsuku Avatar answered May 19 '26 01:05

kiritsuku



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!