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


Scala Right类代码示例

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


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

示例1: AliasSwitching

//设置package包名称以及导入依赖的类
package com.yannick_cw.elastic_indexer4s.elasticsearch.index_ops

import scala.concurrent.{ExecutionContext, Future}
import cats.implicits._
import com.yannick_cw.elastic_indexer4s.Index_results.{IndexError, StageSucceeded}

import scala.util.Right
import scala.util.control.NonFatal

class AliasSwitching(esClient: EsOpsClientApi, waitForElastic: Long, minThreshold: Double, maxThreshold: Double)
  (implicit ec: ExecutionContext) {

  import esClient._

  def switchAlias(alias: String, newIndexName: String): Future[Either[IndexError, StageSucceeded]] = trySwitching(alias, newIndexName)
    .recover { case NonFatal(ex) =>
        Left(IndexError("Could not switch alias.", Some(ex)))
    }

  private def trySwitching(alias: String, newIndexName: String): Future[Either[IndexError, StageSucceeded]] = for {
    _ <- Future(Thread.sleep(waitForElastic))
    oldSize <- latestIndexWithAliasSize(alias)
    newSize <- sizeFor(newIndexName)
    optSwitchRes <- oldSize.traverse(size => switchAliasBetweenIndices(newSize / size.toDouble, alias, newIndexName))
    switchRes <- optSwitchRes match {
      case None => addAliasToIndex(newIndexName, alias)
        .map(_ => Right(NewAliasCreated(s"Added alias $alias to index $newIndexName")))
      case Some(x) => Future.successful(x)
    }
  } yield switchRes

  private def switchAliasBetweenIndices(percentage: Double, alias: String, newIndexName: String): Future[Either[IndexError, StageSucceeded]] =
    if (checkThreshold(percentage)) switchAliasToIndex(alias, newIndexName)
      .map(_ => Right(AliasSwitched(s"Switched alias, new index size is ${(percentage * 100).toInt}% of old index")))
    else Future.successful(Left(IndexError(s"Switching failed, new index size is ${(percentage * 100).toInt}% of old index")))

  private def checkThreshold(percentage: Double): Boolean = minThreshold < percentage && percentage <= maxThreshold
}

object AliasSwitching {
  def apply(esClient: EsOpsClientApi,  minThreshold: Double, maxThreshold: Double, waitForElastic: Long)
    (implicit ec: ExecutionContext): AliasSwitching = new AliasSwitching(esClient, waitForElastic, minThreshold, maxThreshold)
}

case class AliasSwitched(override val msg: String) extends StageSucceeded
case class NewAliasCreated(override val msg: String) extends StageSucceeded 
开发者ID:yannick-cw,项目名称:elastic-indexer4s,代码行数:47,代码来源:AliasSwitching.scala

示例2: loginBinder

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

import commons.models.Login
import play.api.mvc.{PathBindable}

import scala.util.Right

package object binders {
  implicit def loginBinder(implicit stringBinder: PathBindable[String]) = new PathBindable[Login] {

    override def bind(key: String, value: String) : Either[String, Login] = {
      stringBinder.bind("login", value) match {
        case Right(login) => Right(Login(login))
        case _ => Left("Unable to bind login.")
      }
    }

    override def unbind(key: String, login: Login): String = stringBinder.unbind("login", login.value)

  }
} 
开发者ID:Dasiu,项目名称:play-framework-scala-example-project,代码行数:22,代码来源:package.scala

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

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

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

示例6: TransferTransactionDiff

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

import cats.implicits._
import com.wavesplatform.settings.FunctionalitySettings
import com.wavesplatform.state2._
import com.wavesplatform.state2.reader.StateReader
import scorex.account.Address
import scorex.transaction.ValidationError
import scorex.transaction.ValidationError.GenericError
import scorex.transaction.assets.TransferTransaction

import scala.util.Right

object TransferTransactionDiff {
  def apply(state: StateReader, s: FunctionalitySettings, blockTime: Long, height: Int)(tx: TransferTransaction): Either[ValidationError, Diff] = {
    val sender = Address.fromPublicKey(tx.sender.publicKey)

    val isInvalidEi = for {
      recipient <- state.resolveAliasEi(tx.recipient)
      portfolios = (
        tx.assetId match {
          case None => Map(sender -> Portfolio(-tx.amount, LeaseInfo.empty, Map.empty)).combine(
            Map(recipient -> Portfolio(tx.amount, LeaseInfo.empty, Map.empty))
          )
          case Some(aid) =>
            Map(sender -> Portfolio(0, LeaseInfo.empty, Map(aid -> -tx.amount))).combine(
              Map(recipient -> Portfolio(0, LeaseInfo.empty, Map(aid -> tx.amount)))
            )
        }).combine(
        tx.feeAssetId match {
          case None => Map(sender -> Portfolio(-tx.fee, LeaseInfo.empty, Map.empty))
          case Some(aid) =>
            Map(sender -> Portfolio(0, LeaseInfo.empty, Map(aid -> -tx.fee)))
        }
      )
      assetIssued = tx.assetId match {
        case None => true
        case Some(aid) => state.assetInfo(aid).isDefined
      }
      feeAssetIssued = tx.feeAssetId match {
        case None => true
        case Some(aid) => state.assetInfo(aid).isDefined
      }
    } yield (portfolios, blockTime > s.allowUnissuedAssetsUntil && !(assetIssued && feeAssetIssued))

    isInvalidEi match {
      case Left(e) => Left(e)
      case Right((portfolios, invalid)) =>
        if (invalid)
          Left(GenericError(s"Unissued assets are not allowed after allowUnissuedAssetsUntil=${s.allowUnissuedAssetsUntil}"))
        else
          Right(Diff(height, tx, portfolios))
    }
  }
} 
开发者ID:wavesplatform,项目名称:Waves,代码行数:56,代码来源:TransferTransactionDiff.scala

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

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

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

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

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

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

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