franklinchou/learnings

[chore] Add collect

darwinyip opened this issue · 1 comments


// From Seq[Try[Option[Long]]]
// To Array[Long] <-- don't use this

import scala.util.{Try, Failure, Success}

def seq2arr(in: Seq[Try[Option[Long]]]): Array[Long] = {
  in
    .flatMap(_.toOption)
    .collect {
      case s if s.isDefined => s.get // Type safe because of isDefined
    }
    .toArray
}



val q2 = Seq(Success(Some(1L)), Failure(new Exception("woops")), Success(Some(2L)))
val q = Seq(Success(Some(1L)), Failure(new Exception("woops")), Success(None))

seq2arr(q)

assert(seq2arr(q2).length == 2)

The collect method takes a Partial Function as its parameter and applies it to all the elements in the collection to create a new collection which satisfies the Partial Function. See Partial Functions.