当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Scala Either.left用法及代码示例


left 方法(或属性)属于util.Either类(class),其相关用法说明如下。

用法:

def left: LeftProjection[A, B]

将此 Either 投影为 Left.

这允许 for-comprehensions 在 Either 实例的左侧,颠倒 Either 的通常 right-bias。

例如

for (s <- Left("flower").left) yield s.length // Left(6)

继续与 scala.Option 类比,LeftProjection 声明 Left 在某些代码中应该类似于 Some

// using Option
def interactWithDB(x: Query): Option[Result] =
  try Some(getResultFromDatabase(x))
  catch {
    case _: SQLException => None
  }

// this will only be executed if interactWithDB returns a Some
val report = for (result <- interactWithDB(someQuery)) yield generateReport(result)
report match {
  case Some(r) => send(r)
  case None    => log("report not generated, not sure why...")
}

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

 // run a report only if interactWithDB returns a Right
 val report = for (result <- interactWithDB(someQuery)) yield generateReport(result)
 report match {
   case Right(r) => send(r)
   case Left(e)  => log(s"report not generated, reason was $e")
 }
 // only report errors
 for (e <- interactWithDB(someQuery).left) log(s"query failed, reason was $e")

源码:

Either.scala

相关用法


注:本文由纯净天空筛选整理自scala-lang.org大神的英文原创作品 Either.left。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。