Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala - evaluate function calls sequentially until one return

Tags:

scala

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
like image 613
Johnny Avatar asked Nov 08 '17 10:11

Johnny


2 Answers

I'd use an easier approach, though the other Answers use more elaborate language features. Just use Option() to catch the null, chain with orElse. I'm assuming methods convertX(d:DataX):Data for explicit conversion. As it might not be found at all we return an Option

def mainCall(id: UUID): Option[Data] {
  Option(maybeMyDataInEndpoint1(id)).map(convertA)
  .orElse(Option(maybeMyDataInEndpoint2(id)).map(convertB))
  .orElse(Option(maybeMyDataInEndpoint3(id)).map(convertC))
}
like image 59
Ossip Avatar answered Sep 28 '22 22:09

Ossip


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)
like image 43
chengpohi Avatar answered Sep 28 '22 22:09

chengpohi