Questions tagged «either»

3
为什么要使用(检查过的)异常之一?
不久之前,我开始使用Scala而不是Java。对我来说,在这些语言之间进行“转换”过程的一部分是学习使用Eithers而不是(checked)Exceptions。我已经用这种方式编码了一段时间,但是最近我开始怀疑这是否真的是更好的方法。 一个主要的优点Either拥有Exception更好的性能; 一个Exception需要建立一个堆栈跟踪和被抛出。据我了解,虽然Exception不是必须的,但构建堆栈跟踪是必需的。 但随后,人们总是可以构建/继承Exceptions的scala.util.control.NoStackTrace,更是这样,我看到很多的情况下,其中的左侧Either实际上是一个Exception(免收性能提升)。 另一个优点Either是编译器安全。Scala编译器不会抱怨未处理Exception的(不同于Java的编译器)。但是,如果我没记错的话,那么这个决定就是用与本主题中讨论的相同的推理来推理的,所以... 在语法方面,我觉得Exception-style更清晰。检查以下代码块(均实现相同的功能): Either 样式: def compute(): Either[String, Int] = { val aEither: Either[String, String] = if (someCondition) Right("good") else Left("bad") val bEithers: Iterable[Either[String, Int]] = someSeq.map { item => if (someCondition(item)) Right(item.toInt) else Left("bad") } for { a <- aEither.right bs <- reduce(bEithers).right ignore <- validate(bs).right …
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.