Scala - evaluate function calls sequentially until one return

Viewed 1258

I have a few 'legacy' endpoints that can return the Data I'm looking for.

def mainCall(id): Data {

    maybeMyDataInEndpoint1(id: UUID): DataA

    maybeMyDataInEndpoint2(id: UUID): DataB

    maybeMyDataInEndpoint3(id: UUID): DataC
}
  • null can be returned if no DataX found
  • return types for each method are different. There are a convert method that converting each DataX to unified Data.
  • The endpoints are not Scala-ish

What is the best Scala approach to evaluate those method calls sequentially until I have the value I need?

In pseudo I would do something like:

val myData = maybeMyDataInEndpoint1 getOrElse maybeMyDataInEndpoint2 getOrElse maybeMyDataInEndpoint3
5 Answers

Maybe You can lift these methods as high order functions of Lists and collectFirst, like:

  val fs = List(maybeMyDataInEndpoint1 _, maybeMyDataInEndpoint2 _, maybeMyDataInEndpoint3 _)

  val f = (a: UUID) => fs.collectFirst {
    case u  if u(a) != null => u(a)
  }
  r(myUUID)
Related