Skip to content

Commit

Permalink
added toValidated to TrySyntax
Browse files Browse the repository at this point in the history
  • Loading branch information
gagandeepkalra committed Aug 24, 2020
1 parent b0331ee commit 2dbd01e
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions core/src/main/scala/cats/syntax/TrySyntax.scala
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package cats
package syntax

import cats.data.Validated
import cats.data.Validated.{Invalid, Valid}

import scala.util.Try

trait TrySyntax {
Expand Down Expand Up @@ -28,4 +31,23 @@ final class TryOps[A](private val self: Try[A]) extends AnyVal {
def liftTo[F[_]](implicit F: ApplicativeError[F, Throwable]): F[A] =
F.fromTry(self)

/**
* transforms the try to a Validated[Throwable, A] instance
*
* {{{
* scala> import cats.syntax.try_._
* scala> import cats.data.Validated
* scala> import util.Try
*
* scala> val s: Try[Int] = Try(3)
* scala> s.toValidated
* res0: Validated[Throwable, Int] = Valid(3)
*
* scala> val f: Try[Int] = Try(throw new Throwable("boo"))
* scala> f.toValidated
* res0: Validated[Throwable, Int] = Invalid(java.lang.Throwable: boo)
* }}}
*/
def toValidated: Validated[Throwable, A] = self.fold(Invalid(_), Valid(_))

}

0 comments on commit 2dbd01e

Please sign in to comment.