score:0

Accepted answer

I guess you mean Seq, not Map.

You could use Seq instead of if sequence here, though I don't think its readable.

You should use getOrElse after find. Assuming each lengthyOperationN is a function:

seq.find(_._1).map{_._2}.getOrElse(lastLengthyOperation).apply()

score:0

The problem with your approach is that you have laziness in the wrong spot. When you declare

lazy val seq = Seq(
  condition1 -> lengthyOperation1,
  ...
)

then once you touch seq, the whole sequence is evaluated with all its lengthy operations, no matter which of them you touch. Sequence is strict in its elements.

You can do what you want using Streams, but I guess it's easier to do it using Options, which are designed for this purpose. Let's just declare a helper implicit function on options. If it's called on Some, it doesn't do anything. If it's called on None, it checks a condition and if it's satisfied, returns Some(result):

implicit class IfOption[A](opt: Option[A]) {
  def ?>[B >: A](condition: Boolean, result: => B): Option[B] =
    opt.orElse(if (condition) Some(result) else None);
}

Now we can do things like

println(
    None
      ?> (1 != 1, "A")
      ?> (2 == 2, "B")
      ?> (3 == 2, "C")
)

where the type of the printed expression is Option[String] and prints Some(B), or

println(
    None
      ?> (1 != 1, "Yes")
      ?> (2 != 2, "No")
      ?> (3 != 2, "heck")
      getOrElse ("ah")
)

where the type is just "String".


Related Query

More Query from same tag