dictionary - Scala - graceful map lookup failure -
let's want map, if fail value in, should trigger abort of whole procedure.
e.g. (simplified):
def mymethod = { val res = foo(map[string,string](("hello" -> "hello")),false) if(!res) println("world!") } def foo(mymap:map[string,string],mydefault:boolean):boolean = { val actualdefault = baz(mydefault) val m = mymap.withdefault{ case _ => return actualdefault } bar((s:string) => m(s)) return true } def bar(lookup:string => string):unit = { print(lookup("hello") + " ") println(lookup("world")) } def baz(mydefault:boolean):boolean = false the behaviour of perfect in case, bar called many times foo , single error in 1 invocation should result in foo's returning error-independent default value.
but, i'm having serious doubts suggested practice.
is there alternative (better) way achieve this?
it's more idiomatic perform map lookups in option monad. allows stop subsequent lookups once 1 fails, , provide default value. example, if have map:
val mymap = map("foo" -> "bar", "hello" -> "world", "a" -> "b") we can write this:
val result: string = ( { f <- mymap.get("foo") h <- mymap.get("hello") <- mymap.get("a") } yield s"$f $h $a" ).getorelse("my default") and we'll "bar world b". if tried key didn't exist in map, we'd default:
scala> val result: string = ( | { | f <- mymap.get("foo") | x <- mymap.get("x") | h <- mymap.get("hello") | <- mymap.get("a") | } yield s"$f $x $h $a" | ).getorelse("my default") result: string = default i'm not sure understand exact use case, should able rewrite in terms of for-comprehension (or desugared version using map , flatmap mymap.get).
Comments
Post a Comment