當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Scala Right.left用法及代碼示例


left 方法(或屬性)屬於 scala.util.Right 類(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")

繼承自:

util.Either.left

源碼:

Either.scala

相關用法


注:本文由純淨天空篩選整理自scala-lang.org大神的英文原創作品 Right.left。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。