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


Scala Left类代码示例

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


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

示例1: LogMessageReadersTest

//设置package包名称以及导入依赖的类
package x7c1.chaff.process

import org.scalatest.{FreeSpecLike, Matchers}
import x7c1.chaff.process.LogMessage.{Error, Info}
import x7c1.chaff.reader.Reader

import scala.util.{Left, Right}

class LogMessageReadersTest extends FreeSpecLike with Matchers {

  "Seq[R[X, LogMessage]]" - {
    ".uniteSequentially can generate R[X, Unit] that" - {

      val toMessage: Either[ProcessError, Seq[String]] => LogMessage = {
        case Right(lines) => Info(lines mkString "\n")
        case Left(error) => Error(error.cause.getMessage)
      }
      val target: Seq[ProcessRunner] => Seq[Reader[HasProcessLogger, LogMessage]] = {
        _ map (_.lines) map (_ map toMessage)
      }
      "should run readers until Error found" in {
        val runners = Seq(
          ProcessRunner(Seq("ls")),
          ProcessRunner(Seq("foobar"))
        )
        val logger = new BufferedLogger
        target(runners).uniteSequentially run logger

        logger.lines should contain inOrder("[run] ls", "[run] foobar")
      }
      "should stop execution when Error found" in {
        val runners = Seq(
          ProcessRunner(Seq("foobar")),
          ProcessRunner(Seq("ls"))
        )
        val logger = new BufferedLogger
        target(runners).uniteSequentially run logger

        logger.lines should contain("[run] foobar")
        logger.lines shouldNot contain("[run] ls")
      }
    }
  }
} 
开发者ID:x7c1,项目名称:Chaff,代码行数:45,代码来源:LogMessageReadersTest.scala

示例2: PaymentTransactionDiff

//设置package包名称以及导入依赖的类
package com.wavesplatform.state2.diffs

import cats.implicits._
import com.wavesplatform.settings.FunctionalitySettings
import com.wavesplatform.state2.reader.StateReader
import com.wavesplatform.state2.{ByteStr, Diff, LeaseInfo, Portfolio}
import scorex.account.Address
import scorex.transaction.ValidationError.GenericError
import scorex.transaction.{PaymentTransaction, ValidationError}

import scala.util.{Left, Right}

object PaymentTransactionDiff {

  def apply(stateReader: StateReader, height: Int, settings: FunctionalitySettings, blockTime: Long)
           (tx: PaymentTransaction): Either[ValidationError, Diff] = {

    stateReader.paymentTransactionIdByHash(ByteStr(tx.hash)) match {
      case Some(existing) if blockTime >= settings.requirePaymentUniqueIdAfter => Left(GenericError(s"PaymentTx is already registered: $existing"))
      case _ => Right(Diff(height = height,
        tx = tx,
        portfolios = Map(
          tx.recipient -> Portfolio(
            balance = tx.amount,
            LeaseInfo.empty,
            assets = Map.empty)) combine Map(
          Address.fromPublicKey(tx.sender.publicKey) -> Portfolio(
            balance = -tx.amount - tx.fee,
            LeaseInfo.empty,
            assets = Map.empty
          )),
      paymentTransactionIdsByHashes = Map(ByteStr(tx.hash) -> tx.id)
      ))
    }
  }
} 
开发者ID:wavesplatform,项目名称:Waves,代码行数:37,代码来源:PaymentTransactionDiff.scala

示例3: BalanceDiffValidation

//设置package包名称以及导入依赖的类
package com.wavesplatform.state2.diffs

import cats.implicits._
import com.wavesplatform.settings.FunctionalitySettings
import com.wavesplatform.state2.reader.StateReader
import com.wavesplatform.state2.{ByteStr, Diff, LeaseInfo, Portfolio}
import scorex.account.Address
import scorex.transaction.Transaction
import scorex.transaction.ValidationError.AccountBalanceError

import scala.util.{Left, Right}

object BalanceDiffValidation {


  def apply[T <: Transaction](s: StateReader, time: Long, fs: FunctionalitySettings)(d: Diff): Either[AccountBalanceError, Diff] = {

    val changedAccounts = d.portfolios.keySet
    val positiveBalanceErrors: Map[Address, String] = changedAccounts.flatMap(acc => {

      val oldPortfolio = s.accountPortfolio(acc)
      val portfolioDiff = d.portfolios(acc)
      val newPortfolio = oldPortfolio.combine(portfolioDiff)

      val err = if (newPortfolio.balance < 0) {
        Some(s"negative waves balance: $acc, old: ${oldPortfolio.balance}, new: ${newPortfolio.balance}")
      } else if (newPortfolio.assets.values.exists(_ < 0)) {
        Some(s"negative asset balance: $acc, new portfolio: ${negativeAssetsInfo(newPortfolio)}")
      } else if (newPortfolio.effectiveBalance < 0) {
        Some(s"negative effective balance: $acc, old: ${leaseWavesInfo(oldPortfolio)}, new: ${leaseWavesInfo(oldPortfolio)}")
      } else if (newPortfolio.balance < newPortfolio.leaseInfo.leaseOut && time > fs.allowLeasedBalanceTransferUntil) {
        Some(s"leased being more than own: $acc, old: ${leaseWavesInfo(oldPortfolio)}, new: ${leaseWavesInfo(oldPortfolio)}")
      } else None
      err.map(acc -> _)
    }).toMap

    if (positiveBalanceErrors.isEmpty) {
      Right(d)
    } else {
      Left(AccountBalanceError(positiveBalanceErrors))
    }
  }

  private def leaseWavesInfo(p: Portfolio): (Long, LeaseInfo) = (p.balance, p.leaseInfo)

  private def negativeAssetsInfo(p: Portfolio): Map[ByteStr, Long] = p.assets.filter(_._2 < 0)
} 
开发者ID:wavesplatform,项目名称:Waves,代码行数:48,代码来源:BalanceDiffValidation.scala

示例4: GenesisTransactionDiff

//设置package包名称以及导入依赖的类
package com.wavesplatform.state2.diffs

import com.wavesplatform.state2.{Diff, LeaseInfo, Portfolio}
import scorex.transaction.ValidationError.GenericError
import scorex.transaction.{GenesisTransaction, ValidationError}

import scala.util.{Left, Right}

object GenesisTransactionDiff {
  def apply(height: Int)(tx: GenesisTransaction): Either[ValidationError, Diff] = {
    if (height != 1) Left(GenericError("GenesisTransaction cannot appear in non-initial block"))
    else
      Right(Diff(height = height, tx = tx,
        portfolios = Map(tx.recipient -> Portfolio(
          balance = tx.amount,
          LeaseInfo.empty,
          assets = Map.empty))))
  }
} 
开发者ID:wavesplatform,项目名称:Waves,代码行数:20,代码来源:GenesisTransactionDiff.scala

示例5: foldM

//设置package包名称以及导入依赖的类
package com.wavesplatform

import cats.{Monad, Traverse}
import scorex.transaction.ValidationError.GenericError
import scorex.transaction.{Transaction, ValidationError}

import scala.util.{Left, Right, Try}
import scala.language.higherKinds

package object state2 {

  def foldM[G[_], F[_], A, B](fa: F[A], z: B)(f: (B, A) => G[B])(implicit G: Monad[G], F: Traverse[F]): G[B] =
    F.foldLeft(fa, G.pure(z))((gb, a) => G.flatMap(gb)(f(_, a)))

  def safeSum(x: Long, y: Long): Long = Try(Math.addExact(x, y)).getOrElse(Long.MinValue)

  implicit class EitherExt[L <: ValidationError, R](ei: Either[L, R]) {
    def liftValidationError[T <: Transaction](t: T): Either[ValidationError, R] = {
      ei.left.map(e => GenericError(e.toString))
    }
  }

  implicit class EitherExt2[A, B](ei: Either[A, B]) {
    def explicitGet(): B = ei match {
      case Left(value) => throw new Exception(value.toString)
      case Right(value) => value
    }
  }

} 
开发者ID:wavesplatform,项目名称:Waves,代码行数:31,代码来源:package.scala

示例6: Committable

//设置package包名称以及导入依赖的类
package aecor.data

import cats.implicits._
import cats.{ Applicative, Eval, Functor, Monad, Traverse }

import scala.util.{ Left, Right }

final case class Committable[F[_], +A](commit: F[Unit], value: A) {
  def map[B](f: A => B): Committable[F, B] = copy(value = f(value))
  def traverse[G[_], B](f: A => G[B])(implicit G: Functor[G]): G[Committable[F, B]] =
    G.map(f(value))(b => copy(value = b))
  def foldLeft[B](b: B)(f: (B, A) => B): B = f(b, value)
}

object Committable {
  implicit def catsMonadAndTraversInstance[F[_]: Applicative]
    : Monad[Committable[F, ?]] with Traverse[Committable[F, ?]] =
    new Monad[Committable[F, ?]] with Traverse[Committable[F, ?]] {
      override def traverse[G[_], A, B](
        fa: Committable[F, A]
      )(f: (A) => G[B])(implicit evidence$1: Applicative[G]): G[Committable[F, B]] =
        fa.traverse(f)

      override def flatMap[A, B](
        fa: Committable[F, A]
      )(f: (A) => Committable[F, B]): Committable[F, B] =
        f(fa.value)

      override def tailRecM[A, B](
        a: A
      )(f: (A) => Committable[F, Either[A, B]]): Committable[F, B] = {
        val c = f(a)
        c.value match {
          case Left(aa) => tailRecM(aa)(f)
          case Right(b) => c.copy(value = b)
        }
      }

      override def foldLeft[A, B](fa: Committable[F, A], b: B)(f: (B, A) => B): B =
        fa.foldLeft(b)(f)

      override def foldRight[A, B](fa: Committable[F, A], lb: Eval[B])(
        f: (A, Eval[B]) => Eval[B]
      ): Eval[B] = f(fa.value, lb)

      override def pure[A](x: A): Committable[F, A] = Committable.pure(x)
    }
  def pure[F[_]: Applicative, A](a: A): Committable[F, A] = Committable(().pure[F], a)
  def unit[F[_]: Applicative]: Committable[F, Unit] = pure(())
  def collector[F[_], A, B](
    pf: PartialFunction[A, B]
  ): PartialFunction[Committable[F, A], Committable[F, B]] = {
    case c if pf.isDefinedAt(c.value) => c.map(pf)
  }
} 
开发者ID:notxcain,项目名称:aecor,代码行数:56,代码来源:Committable.scala

示例7: main

//设置package包名称以及导入依赖的类
package com.rklick.graphx.process


import com.rklick.graphx.context.GraphXProcess
import com.rklick.graphx.domain.GraphComponent
import com.rklick.graphx.utils.SparkCommon

import scala.util.{Left, Right}


  def main(args: Array[String]) {
    val SCHEMA_OPTIONS = Map("header" -> "true", "inferSchema" -> "true")
    val path = "src/main/resources/graph_data.csv"
    val df = sqlContext.read.format("csv").options(SCHEMA_OPTIONS).load(path)
    val graphComponent = GraphComponent("ID", "User", "Relationship", "RelationId")
    processGraph(df, graphComponent) match {
      case Right(data) => println(s"GraphX process successfully completed.")
        sqlContext.sparkContext.stop()
      case Left(error) => println(s"Error during graphX:::${error}")
        sqlContext.sparkContext.stop()
    }
  }
} 
开发者ID:rklick-solutions,项目名称:graphx-scala,代码行数:24,代码来源:GraphXMainProcess.scala

示例8: 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

示例9: 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

示例10: DeliverySchemeSpec

//设置package包名称以及导入依赖的类
package sangria.parser

import org.scalatest.{Matchers, WordSpec}

class DeliverySchemeSpec extends WordSpec with Matchers {
  "DeliveryScheme" should {
    "by default support `Try`" in {
      import scala.util.{Success, Failure}

      QueryParser.parse("{ field }") shouldBe a [Success[_]]
      QueryParser.parse("}") shouldBe a [Failure[_]]
    }

    "support `Either`" in {
      import sangria.parser.DeliveryScheme.Either
      import scala.util.{Left, Right}

      QueryParser.parse("{ field }") shouldBe a [Right[_, _]]
      QueryParser.parse("}") shouldBe a [Left[_, _]]
    }

    "support exception throwing" in {
      import sangria.parser.DeliveryScheme.Throw
      import sangria.ast.Document

      QueryParser.parse("{ field }") shouldBe a [Document]
      a [SyntaxError] should be thrownBy QueryParser.parse("}")
    }
  }
} 
开发者ID:gitprowl,项目名称:prowlgria,代码行数:31,代码来源:DeliverySchemeSpec.scala

示例11: AskDemoArticleParser

//设置package包名称以及导入依赖的类
package com.akkademy

import akka.actor.Actor
import akka.pattern._
import akka.util.Timeout
import com.akkademy.messages.{SetRequest, GetRequest}

import scala.concurrent.{Future, Await}
import scala.util.{Success, Failure, Either, Left, Right}

class AskDemoArticleParser(cacheActorPath: String,
                           httpClientActorPath: String,
                           articleParserActorPath: String,
                           implicit val timeout: Timeout) extends Actor {
  val cacheActor = context.actorSelection(cacheActorPath)
  val httpClientActor = context.actorSelection(httpClientActorPath)
  val articleParserActor = Await.result(context.actorSelection(articleParserActorPath).resolveOne(), timeout.duration)

  import scala.concurrent.ExecutionContext.Implicits.global

  
      // for (
      //   httpResponse <- (httpClientActor ? uri).mapTo[HttpResponse];
      //   parsedArticle <- (articleParserActor ? ParseHtmlArticle(uri, httpResponse.body)).mapTo[ArticleBody]
      // ) yield Left(parsedArticle)
    }).mapTo[Either[ArticleBody, String]]

    result onComplete {
      case Success(article) =>
        article.fold(x => cacheActor ! SetRequest(uri, x.body), _ => println("cached result!"))
        article.fold(senderRef ! _, senderRef ! _)
      case Failure(e) => senderRef ! akka.actor.Status.Failure(e)
    }
  }
} 
开发者ID:josiah14,项目名称:AkkademyDb,代码行数:36,代码来源:AskDemoArticleParser.scala

示例12: BalanceDiffValidation

//设置package包名称以及导入依赖的类
package com.wavesplatform.state2.diffs

import cats.implicits._
import com.wavesplatform.settings.FunctionalitySettings
import com.wavesplatform.state2.reader.StateReader
import com.wavesplatform.state2.{ByteStr, Diff, LeaseInfo, Portfolio}
import scorex.account.Address
import scorex.transaction.Transaction
import scorex.transaction.ValidationError.AccountBalanceError

import scala.util.{Left, Right}

object BalanceDiffValidation {


  def apply[T <: Transaction](s: StateReader, time: Long, fs: FunctionalitySettings)(tx: T, d: Diff): Either[AccountBalanceError, Diff] = {

    val changedAccounts = d.portfolios.keySet
    val positiveBalanceErrors: Map[Address, String] = changedAccounts.flatMap(acc => {

      val oldPortfolio = s.accountPortfolio(acc)
      val portfolioDiff = d.portfolios(acc)
      val newPortfolio = oldPortfolio.combine(portfolioDiff)

      val err = if (newPortfolio.balance < 0) {
        Some(s"negative waves balance: $acc, old: ${oldPortfolio.balance}, new: ${newPortfolio.balance}")
      } else if (newPortfolio.assets.values.exists(_ < 0)) {
        Some(s"negative asset balance: $acc, new portfolio: ${negativeAssetsInfo(newPortfolio)}")
      } else if (newPortfolio.effectiveBalance < 0) {
        Some(s"negative effective balance: $acc, old: ${leaseWavesInfo(oldPortfolio)}, new: ${leaseWavesInfo(oldPortfolio)}")
      } else if (newPortfolio.balance < newPortfolio.leaseInfo.leaseOut && time > fs.allowLeasedBalanceTransferUntil) {
        Some(s"leased being more than own: $acc, old: ${leaseWavesInfo(oldPortfolio)}, new: ${leaseWavesInfo(oldPortfolio)}")
      } else None
      err.map(acc -> _)
    }).toMap

    if (positiveBalanceErrors.isEmpty) {
      Right(d)
    } else {
      Left(AccountBalanceError(positiveBalanceErrors))
    }
  }

  private def leaseWavesInfo(p: Portfolio): (Long, LeaseInfo) = (p.balance, p.leaseInfo)

  private def negativeAssetsInfo(p: Portfolio): Map[ByteStr, Long] = p.assets.filter(_._2 < 0)
} 
开发者ID:mikepijn,项目名称:wavesnode,代码行数:48,代码来源:BalanceDiffValidation.scala


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