5

I'm have a function which should return nothing (void ) or a String when some conditions are not met.

I try this line Either.left(Void)

    private Either<Void,String> processOrReturnErrorMessage(){
        //Do something  and in some case return a message of failed conditions
        return Either.left(Void);
    }
EFOE
  • 609
  • 1
  • 10
  • 20
  • Why not just return an empty String when you want nothing returned? – Nexevis Aug 28 '19 at 15:54
  • If the situations in which you would return a String are indicative of a failed operation, why don't you throw an exception instead? That's what they're for – JonK Aug 28 '19 at 15:54
  • I'm using vavr to avoid dealing functional case with exception. @Nexevis You are right, it can be a possibility. but the fact is i want to use a more structured way something like result.isLeft(), or even more result.map – EFOE Aug 28 '19 at 16:00
  • Its worth mentioning that `Either` is not Java, its Scala or some other library. – Bonatti Aug 28 '19 at 17:03
  • The library is VAVR as mentioned in the title and in the tag – EFOE Aug 28 '19 at 17:37
  • To express that you use java Optional. Optional.isPresent() means there was some error. You don't need an external lib to express that. – Bruno Negrão Zica Jun 01 '23 at 20:10
  • You are right to express an error it is enough. But the purpose was also to add the type or error encountered and give more context ( without using exceptions). – EFOE Jun 26 '23 at 15:18

2 Answers2

6

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.

Nándor Előd Fekete
  • 6,988
  • 1
  • 22
  • 47
1

you can just return null in case of void.

return right(null);
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103