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

后端 未结 2 1259
-上瘾入骨i
-上瘾入骨i 2021-01-12 05:56

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

2条回答
  •  失恋的感觉
    2021-01-12 06:35

    I use Try[Unit] for that case.

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

    • 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
    

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

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

提交回复
热议问题