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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With