What type of return value should the Scala method have if it can cause / return errors, but has a return type of one?

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

I could, of course, return Either[SomeErrorType, Unit] , but it definitely looks weird.

I could just return Option[SomeErrorType] , but actually it does not look much better (and breaks, perhaps, the existing symmetry with other Either[SomeErrorType, NonUnitReturnType] s.

What is your approach in these cases?

  • def m(): Unit // and implicitly know that exceptions can be thrown? ;
  • def m(): Either[SomeErrorType, Unit] // this is odd ;
  • def m(): Option[SomeErrorType] // this is odd, as it makes it look as the return type of t () on a successful run is an error code.
  • Another thing I can't think of?

thanks

+8
scala
source share
2 answers

I am using Try[Unit] for this 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 raises errors at the application level, encodes some error in the signature and allows the application to process it as a value.
  • against. Option[T] => The option can only encode that the operation was significant or not
  • against. Either[SomeErrorType, Unit] => Try It’s easier to work using monadic constructs.

I used something like this to do checks. (imaginary example)

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

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

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

+10
source share

Another option that has not yet been mentioned is Validated from cats . All the options mentioned so far ( Try , Either , Option ) are monads, and Validated is an application functor. In practice, this means that you can accumulate errors from several methods that return Validated , and you can perform multiple checks in parallel. This may not apply to you, and this is a little orthogonal to the original question, but I still think it's worth mentioning in this context.

As for the original question, using the Unit return type for the side effect function is fine. The fact that this function can also return an error should not bother you when you determine the return type is β€œreal” (right, successful, etc.). Therefore, if I were selected from your original parameters, I would go for Either[Error, Unit] . It definitely doesn't look strange to me, and if someone sees any flaws in it, I would like to know them.

+2
source share

All Articles