WestCoastProjects
WestCoastProjects

Reputation: 63062

Clean/idiomatic/concise way to return an Option from a map in Scala

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

Answers (2)

Gangstead
Gangstead

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

Eugene Zhulenev
Eugene Zhulenev

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

Related Questions