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

Scala example source code file (IoExceptionOr.scala)

This example Scala source code file (IoExceptionOr.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

boolean, ioexception, ioexceptionor, none, option, some

The IoExceptionOr.scala Scala example source code

package scalaz
package effect

sealed abstract class IoExceptionOr[A] {

  import IoExceptionOr._

  def fold[X](ioException: IoException => X, or: A => X): X

  def map[B](f: A => B): IoExceptionOr[B] =
    fold(ioException, a => IoExceptionOr(f(a)))

  def flatMap[B](f: A => IoExceptionOr[B]): IoExceptionOr[B] =
    fold(ioException, f)

  def forall(p: A => Boolean): Boolean =
    fold(_ => true, p)

  def exists(p: A => Boolean): Boolean =
    fold(_ => false, p)

  def toOption: Option[A] =
    fold(_ => None, Some(_))

  def valueOr(a: => A): A =
    fold(_ => a, x => x)
}

object IoExceptionOr {
  def apply[A](a: => A): IoExceptionOr[A] =
    try {
      ioExceptionOr(a)
    } catch {
      case e: java.io.IOException => ioException(e)
    }
  def unapply[A](ioExceptionOr: IoExceptionOr[A]) = ioExceptionOr.toOption

  type IoException =
  java.io.IOException

  def ioException[A]: IoException => IoExceptionOr[A] =
    e => new IoExceptionOr[A] {
      def fold[X](ioException: IoException => X, or: A => X) =
        ioException(e)
    }

  def ioExceptionOr[A](a: A): IoExceptionOr[A] = new IoExceptionOr[A] {
    def fold[X](ioException: IoException => X, or: A => X) =
      or(a)
  }

}

Other Scala examples (source code examples)

Here is a short list of links related to this Scala IoExceptionOr.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.