I have a map and want to:
- retrieve value without handling Option
- log a message when there is no such the key.
- nice to return a default value ( in addition to log a message) when the key is not present. This is optional because when the code fails here, it should not continue further.
I have several ways of doing it
val map: Map[String, Int] // defined as such for simplification
// 1 short but confusing with error handling
def getValue(key: String): Int = {
map.getOrElse(key, scala.sys.error(s"No key '$key' found"))
}
// in case you don't know scala.sys.error
package object sys {
def error(message: String): Nothing = throw new RuntimeException(message)
}
// 2 verbose
def getValue(key: String): Int = {
try {
map(key)
} catch {
case _: Throwable => scala.sys.error(s"No key '$key' found")
}
}
// 3 Try and pattern matching
import scala.util.{Failure, Success, Try}
def getValue(key: String): Int = {
Try(map(key)) match{
case Success(value) => value
case Failure(ex) => sys.error(s"No key '$key' found ${ex.getMessage}")
}
}
Others solutions are welcomed. I'm looking for conciseness without being cryptic. Using standard scala ( no need for Scalaz, Shapeless ... )
Inspirations :