如果 Scala 方法可以抛出/返回错误但具有 Unit 返回类型,那么它应该具有什么返回类型? [英] What return type should a Scala method have if it can throw/return errors but has Unit return type?

查看:30
本文介绍了如果 Scala 方法可以抛出/返回错误但具有 Unit 返回类型,那么它应该具有什么返回类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So usually when we run a method that can both fail and return a value, we can encode our method return type as Either[SomeErrorType, ReturnType]. But many times we're running a method for its side effects, so the return type is Unit.

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

I could of course return an Either[SomeErrorType, Unit] but that definitely looks odd.

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

I could also just return an Option[SomeErrorType] but it doesn't really look a lot better (and breaks a possibly existing symmetry with other Either[SomeErrorType, NonUnitReturnType]s.

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

What's your approach in these cases?

  1. def m(): Unit//并且隐含地知道可以抛出异常?;
  2. def m(): Each[SomeErrorType, Unit]//这是奇数;
  3. def m(): Option[SomeErrorType]//这很奇怪,因为它使它看起来像成功运行时m()的返回类型是错误代码.
  4. 其他我想不到的?

谢谢

推荐答案

对于这种情况,我使用 Try[Unit].

I use Try[Unit] for that case.

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

It encodes that the result of the method either succeeds or fails with some Exception, which can be further processed.

  • vs T =>Unit Try 将错误提升到应用程序级别,在签名中编码可能会出现一些错误并允许应用程序将其作为值处理.
  • 对比Option[T] => Option 只能编码操作是否有值
  • 对比Either[SomeErrorType, Unit] => Try 使用一元结构更容易.
  • vs T => Unit Try lifts errors to the application level, encoding in the signature that some error can be expected and allowing the application to handle it as a value.
  • vs. Option[T] => Option is only able to encode that the operation had a value or not
  • vs. Either[SomeErrorType, Unit] => Try It's easier to work with using monadic constructions.

我使用过类似的东西来实现检查.(假想的例子)

I've used something like this to implement checks. (imaginary example)

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

其中每个检查的形式为:Entity =>尝试[单位]

where each check is of the form: Entity => Try[Unit]

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

This will return the entity if all checks pass of the first error that failed the check.

这篇关于如果 Scala 方法可以抛出/返回错误但具有 Unit 返回类型,那么它应该具有什么返回类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆