当前位置: 首页>>代码示例>>Scala>>正文


Scala Either类代码示例

本文整理汇总了Scala中scala.util.Either的典型用法代码示例。如果您正苦于以下问题:Scala Either类的具体用法?Scala Either怎么用?Scala Either使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Either类的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。

示例1: Utils

//设置package包名称以及导入依赖的类
package com.trainologic.samples.petclinic
import monix.eval.{ Task => MonixTask }
import scalaz.concurrent.{ Task => ScalazTask }
import monix.execution.Scheduler
import scala.util.{ Try, Right, Left, Either,Success, Failure }
import fs2.util.Suspendable
import fs2.util.Catchable
import fs2.util.Attempt

object Utils {

  implicit class TryPimp[T](t: Try[T]) {
    def toEither: Either[Throwable, T] = t.transform(s => Success(Right(s)), f => Success(Left(f))).get
  }
  
  implicit val taskCatchable  = new Suspendable[MonixTask] with Catchable[MonixTask]{
    override def pure[A](a: A): MonixTask[A] = MonixTask.pure(a)
    override def flatMap[A, B](a: MonixTask[A])(f: A => MonixTask[B]) = a.flatMap(f)
    override def suspend[A](fa: => MonixTask[A]): MonixTask[A] = MonixTask.suspend(fa)
    override def fail[A](err: Throwable): MonixTask[A] = MonixTask.raiseError(err)
    override def attempt[A](fa: MonixTask[A]): MonixTask[Attempt[A]] = fa.materialize.map(_.toEither)
  }
  
  
  
  
  
  
  

  implicit def monixTask2scalazTask[A](mtask: MonixTask[A])(implicit s: Scheduler): ScalazTask[A] = {
    import scalaz.{ \/, -\/, \/- }
    scalaz.concurrent.Task.async[A](
      register => mtask.runAsync { tr =>
        tr match {
          case Success(r) => register(\/-(r))
          case Failure(t) => register(-\/(t))
        }
      })
  }
} 
开发者ID:Trainologic,项目名称:petclinic_eff,代码行数:42,代码来源:Utils.scala

示例2: Failed

//设置package包名称以及导入依赖的类
import scala.util.{Either, Right, Left}

case class Failed(msg: String)

object UnitExample {

  def write(): Either[Failed, Unit] = {
    Right( () )
  }

  def log(): Either[Failed, Unit] = {
    Left(Failed("during log"))
  }

  def cleanup(): Unit = {}

  def run(): Either[Failed, Unit] =
   write().map(_ => log())
}

object MarkerExample {

  sealed trait Success
  object Success extends Success

  def write(): Either[Failed, Success] = {
    Right(Success)
  }

  def log(): Either[Failed, Success] = {
    Left(Failed("in log"))
    //Right(success)
  }

  def run(): Either[Failed, Success] =
    for {
      _ <- write()
      _ <- log()
    } yield Success

  def run0(): Either[Failed, Success] = {
    write().flatMap(_ => log())
    // Hurrah! Wont' compile -> write().map(_ => log())
  }
}

object Main {

  def main(args: Array[String]): Unit = {
    println("\nUnit example:")
    println( UnitExample.run() )
    println("\n\nMarker-based example:")
    println( MarkerExample.run() )
    println("\n")
  }

} 
开发者ID:d6y,项目名称:discarded-values,代码行数:58,代码来源:main.scala


注:本文中的scala.util.Either类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。