0
点赞
收藏
分享

微信扫一扫

Scala Either Left Right

腊梅5朵 2022-02-10 阅读 48

Either

官网Either

  • 代表两个可能类型的值,两个之间没有交集
  • 是scala.util.Left or scala.util.Right 的实现类
  • 可以做scala.option的替换 ,scala.util.Left 替换scala.None,scala.util.Right替换scala.Some
  • 时实践中使用scala.util.Left作为Failure
  • scala.util.Right作为成功的值

官方demo

object EitherDemo {
  def main(args: Array[String]): Unit = {
    val in = readLine("Type Either a string or an Int: ")
    val result: Either[String,Int] =
      try Right(in.toInt)
      catch {
        case e: NumberFormatException => Left(in)
      }
    
    //判断Either实例是不是Right类
    println(result.isRight)
    println(result.isLeft)
    
    //得到right的值
//    println(result.right.get)
    println(result.left.get)
    result match {
      case Right(x) => println(s"You passed me the Int: $x, which I will increment. $x + 1 = ${x+1}")
      case Left(x)  => println(s"You passed me the String: $x")
    }
  }
  
}

Either is right-biased

  • Right被设定为默认case。
  • Left 的map 和flatMap操作返回不变的Left
scala> def doubled(i: Int) = i * 2
def doubled(i: Int): Int

scala> Right(42).map(doubled)
val res0: scala.util.Either[Nothing,Int] = Right(84)

// Left map 操作不会改变
scala> Left(42).map(doubled)
val res1: scala.util.Either[Int,Int] = Left(42)
举报

相关推荐

0 条评论