假设我正在使用Scala项目中的Java库.Java库在所有地方都抛出了异常,但我觉得让它们"在Scala世界中"传播感觉不舒服,因为无法确定Scala方法可以抛出什么异常(除非记录它们).所以这是我倾向于编写的代码:
def doesNotThrowExceptions(parameter: String): Either[Throwable, T] =
catching(classOf[IOException], classOf[NoSuchAlgorithmException]) either {
// Code calling the Java library
// Code generating a value of type T
}
Run Code Online (Sandbox Code Playgroud)
然后,通常,我将使用Either.RightProjection.flatMap链接返回Either[Throwable, ...]或Either.RightProjection.map混合返回Either[Throwable, ...]方法和其他方法的方法.或者只是Either.fold对Throwable价值做点什么.但不知怎的,这仍然感觉不完全正确.
这是处理Scala中Java异常的最"惯用"方式吗?有没有更好的方法?
如果值为Some(...),则执行副作用的最常用方法是什么?如果值为None,则执行另一个副作用.这是我目前倾向于写的内容:
def doSideEffectA(value: Int) {
// ...
}
def doSideEffectB() {
// ...
}
def doSideEffect(valueOption: Option[Int]) {
valueOption map { value =>
doSideEffectA(value)
} getOrElse {
doSideEffectB()
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,如果我没有做任何事情,如果valueOption是None,那么这就是我写的:
def doSideEffectNothingIfNone(valueOption: Option[Int]) {
valueOption foreach { value =>
doSideEffectA(value)
}
}
Run Code Online (Sandbox Code Playgroud)
map/getOrElse通常不用于副作用上下文,而foreach是.我对valueOption map {...} getOrElse {...}返回Unit感到不舒服,因为我没有从我的Option [Int]中"得到"任何东西.