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 Right.joinLeft用法及代码示例
- Scala Right.joinRight用法及代码示例
- Scala Right.exists用法及代码示例
- Scala Right.filterOrElse用法及代码示例
- Scala Right.swap用法及代码示例
- Scala Right.toOption用法及代码示例
- Scala Right.withLeft用法及代码示例
- Scala Right.forall用法及代码示例
- Scala Right.orElse用法及代码示例
- Scala Right.fold用法及代码示例
- Scala Right.contains用法及代码示例
- Scala Right.getOrElse用法及代码示例
- Scala Right.foreach用法及代码示例
- Scala Right.map用法及代码示例
- Scala Right.flatten用法及代码示例
- Scala Right.toSeq用法及代码示例
- Scala RightPartitionMapped.collectFirst用法及代码示例
- Scala RightPartitionMapped.sizeIs用法及代码示例
- Scala RightPartitionMapped.partitionMap用法及代码示例
- Scala RightPartitionMapped.transpose用法及代码示例
- Scala RightPartitionMapped.unzip3用法及代码示例
- Scala RightPartitionMapped.tails用法及代码示例
- Scala RightProjection.filter用法及代码示例
- Scala RightPartitionMapped.sizeCompare用法及代码示例
- Scala RightProjection.get用法及代码示例
注:本文由纯净天空筛选整理自scala-lang.org大神的英文原创作品 Right.left。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。