繁体   English   中英

如果 Scala 方法可以抛出/返回错误但具有 Unit 返回类型,那么它应该具有什么返回类型?

[英]What return type should a Scala method have if it can throw/return errors but has Unit return type?

所以通常当我们运行一个既可以失败又可以返回值的方法时,我们可以将我们的方法返回类型编码为Either[SomeErrorType, ReturnType] 但是很多时候我们为了它的副作用运行一个方法,所以返回类型是Unit

我当然可以返回一个Either[SomeErrorType, Unit]但这绝对看起来很奇怪。

我也可以只返回一个Option[SomeErrorType]但它看起来并没有好多少(并且打破了与其他Either[SomeErrorType, NonUnitReturnType]一个可能存在的对称性Either[SomeErrorType, NonUnitReturnType] s。

在这些情况下你的方法是什么?

  1. def m(): Unit // and implicitly know that exceptions can be thrown? ;
  2. def m(): Either[SomeErrorType, Unit] // this is odd
  3. def m(): Option[SomeErrorType] // this is odd, as it makes it look as the return type of on a successful run is an error code. m() def m(): Option[SomeErrorType] // this is odd, as it makes it look as the return type of on a successful run is an error code.
  4. 其他我想不到的?

谢谢

在这种情况下,我使用Try[Unit]

它编码该方法的结果要么成功要么失败,并带有一些Exception ,可以进一步处理。

  • vs T => Unit Try将错误提升到应用程序级别,在签名中编码可能会出现一些错误并允许应用程序将其作为值处理。
  • vs. Option[T] => Option 只能编码操作是否有值
  • vs. Either[SomeErrorType, Unit] => Try使用 monadic 结构更容易工作。

我用过这样的东西来实现检查。 (假想的例子)

for {
    entity <- receiveEntity // Try[Entity]
    _ <- isRelational(entity)
    _ <- isComplete(entity)
    _ <- isStable(entity)
} yield entity

其中每个检查的形式为: Entity => Try[Unit]

如果所有检查都通过了检查失败的第一个错误,这将返回entity

另一种尚未提及的选项是从Validated 到目前为止提到的所有选项( TryEitherOption )都是 monad,而Validated是一个应用函子。 实际上,这意味着您可以从多个返回Validated方法中累积错误,并且您可以并行执行多个验证。 这可能与您无关,这与原始问题有点正交,但我仍然觉得在这种情况下值得一提。

至于最初的问题,将Unit返回类型用于副作用函数是完全没问题的。 当您定义“真实”(正确、成功等)返回类型时,此函数也可以返回错误这一事实不应妨碍您。 因此,如果我要从您的原始选项中进行选择,我会选择Either[Error, Unit] 它对我来说绝对不奇怪,如果有人看到它的任何缺点,我想知道它们。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM