获得任何一种的价值 [英] Getting Value of Either

查看:61
本文介绍了获得任何一种的价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了使用match之外,还有一种类似于Option的方式来getOrElseRightLeft值的实际内容吗?

Besides using match, is there an Option-like way to getOrElse the actual content of the Right or Left value?

scala> val x: Either[String,Int] = Right(5)
scala> val a: String = x match { 
                                case Right(x) => x.toString
                                case Left(x) => "left" 
                       }
a: String = 5

推荐答案

我不太喜欢Either,因此我对它并不十分熟悉,但是我相信您正在寻找预测结果:either.left.getOrElseeither.right.getOrElse.

I don't particularly like Either and as a result I'm not terribly familiar with it, but I believe you're looking for projections: either.left.getOrElse or either.right.getOrElse.

请注意,投影也可以用于理解中.这是直接来自文档的示例:

Note that projections can be used in for-comprehensions as well. This is an example straight from the documentation:

def interactWithDB(x: Query): Either[Exception, Result] =
  try {
    Right(getResultFromDatabase(x))
  } catch {
    case ex => Left(ex)
  }

// this will only be executed if interactWithDB returns a Right
val report =
  for (r <- interactWithDB(someQuery).right) yield generateReport(r)
if (report.isRight)
  send(report)
else
  log("report not generated, reason was " + report.left.get)

这篇关于获得任何一种的价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆