alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Scala example source code file (Try.scala)

This example Scala source code file (Try.scala) is included in the alvinalexander.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Scala by Example" TM.

Learn more about this Scala project at its project page.

Java - Scala tags/keywords

failure, isofunctortemplate, success, throwable, try, tryfunctions, tryinstances, validation, validationnel

The Try.scala Scala example source code

package scalaz
package std

import Isomorphism.{<~>, IsoFunctorTemplate}
import scala.util.{Failure, Success, Try}

trait TryFunctions {
  def cata[A, B](t: Try[A])(success: A => B, failure: Throwable => B): B =
    t match {
      case Success(a) => success(a)
      case Failure(t) => failure(t)
    }

  def toDisjunction[A](t: Try[A]): Throwable \/ A =
    cata(t)(\/.right, \/.left)

  def fromDisjunction[T <: Throwable, A](d: T \/ A): Try[A] =
    d.fold(Failure.apply, Success.apply)

  def toValidation[A](t: Try[A]): Validation[Throwable, A] =
    cata(t)(Validation.success, Validation.failure)

  def toValidationNel[A](t: Try[A]) : ValidationNel[Throwable, A] =
    cata(t)(Validation.success, Validation.failureNel)

  def fromValidation[T <: Throwable, A](v: Validation[T, A]) : Try[A] =
    v.fold(Failure.apply, Success.apply)
}

trait TryInstances {
  import scalaz.std.{`try` => t}

  val tryDisjunctionIso: Try <~> λ[α => Throwable \/ α] =
    new IsoFunctorTemplate[Try, Throwable \/ ?] {
      def to[A](fa: Try[A]) = t.toDisjunction(fa)
      def from[A](ga: Throwable \/ A) = t.fromDisjunction(ga)
    }

  val tryValidationIso: Try <~> λ[α => Validation[Throwable, α]] =
    new IsoFunctorTemplate[Try, Validation[Throwable, ?]] {
      def to[A](fa: Try[A]) = t.toValidation(fa)
      def from[A](v: Validation[Throwable, A]) = t.fromValidation(v)
    }
}

object `try` extends TryFunctions with TryInstances

Other Scala examples (source code examples)

Here is a short list of links related to this Scala Try.scala source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.