Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add toValidated to TrySyntax #3579

Merged
merged 1 commit into from
Aug 25, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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(_))

}