0

While thinking about my previous question, I realized I ought to be able to write something like the following:

  val empty: Try[B, forall types B] = Failure(new RuntimeException("empty"))
  def firstSuccess[A, B](xs: Iterable[A], f: A => Try[B]): Try[B] = {
    xs.foldLeft(empty)((e, a) => e.recoverWith { case _ => f(a) })
  }

because a Failure is a valid Try[B] for any type B. Is there a way to achieve my "B, forall types B" in Scala?

Community
  • 1
  • 1
jonderry
  • 23,013
  • 32
  • 104
  • 171

1 Answers1

2

You can use the Nothing type since everything in scala is Nothing:

  val empty = Failure[Nothing](new RuntimeException("empty"))
  def firstSuccess[A, B](xs: Iterable[A], f: A => Try[B]): Try[B] = {
    xs.foldLeft[Try[B]](empty)((e, a) => e.recoverWith { case _ => f(a) })
  }

You do have to sprinkle in a few types here and there though (added type parameter to foldLeft).

Noah
  • 13,821
  • 4
  • 36
  • 45