There's a type for that in vavr, and it's called Option
. You can return Option.none()
in case there is no error, and return Option.some(errorMessage)
in case there is an error.
If you still want to use Either
, I would recommend to use the left side for errors and the right side for values (the happy path), because Either
is right biased, so the map
and flatMap
methods act on Either
only if it's a right value. In your case, since there's no value to return (i.e. a void), you can use Either<String, Void>
, and return Either.right(null)
for the success case, since null
is the only inhabitant of the type Void
(null is inhabitant of all non-primitive types in Java, as of now, unfortunately).
Or you could introduce a new type called Unit
with a single inhabitant (i.e. a singleton), use Either<String, Unit>
for your return type and return Either.right(Unit.instance())
to signal the lack of meaningful return value and avoid returning null
values, because returning null
values is kind of ugly.
Either
is not Java, its Scala or some other library. – Edgardoedge