Reputation: 63062
In the following code is there an inline way to return either the first value or None? Handling of Options has seemed more verbose than anticipated.
def findBySqlName(sqlName : String) = {
map.iterator.find{ case (cname, col) =>
col.sqlName == sqlName
}.someThingInlineHereThatReturnsTheFirstValueOrNoneIfEmpty
}
Upvotes: 1
Views: 73
Reputation: 4182
I know you've already accepted an answer, but in you can use collectFirst
to do find
and map
in one step:
def findBySqlName(sqlName : String) = {
map.collectFirst({ case (cname, col) if (col.sqlName == sqlName) => col._2 })
}
Upvotes: 1
Reputation: 9734
Just map.find?
val map = Map(1 -> "a", 2 -> "b")
def findByValue(v: String) = map.find(_._2 == v)
println(findByValue("a"))
println(findByValue("c"))
In your case to get value:
def findBySqlName(sqlName : String) = {
map.iterator.find{ case (cname, col) =>
col.sqlName == sqlName
}.map(_._2)
}
Upvotes: 3