Search code examples
scalascala-option

Scala : Nested getOrElse


I would like to create a method that takes as arguments an array of options and a default value and return the first non empty option otherwise the default value :

def customGetOrElse[T](options : Array[Option[T]], defaultValue : T) : T = {
  // Example if options contain 2 elements
  options(0).getOrElse(options(1).getOrElse(defaultValue))
  // If options contain 3 elements
  options(0).getOrElse(options(1).getOrElse(options(2).getOrElse(defaultValue)))
}

But I am struggling to make this method working for any size of the array. Any ideas ?

Thanks!


Solution

  • def customGetOrElse[T](options : Array[Option[T]], defaultValue : T) : T = {
      options.find(_.isDefined).flatten.getOrElse(defaultValue)
    }