How to return Either a void or a String with vavr
Asked Answered
S

2

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);
    }
Scathing answered 28/8, 2019 at 15:47 Comment(7)
Why not just return an empty String when you want nothing returned?Fortenberry
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 forSchauer
I'm using vavr to avoid dealing functional case with exception. @Fortenberry 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.mapScathing
Its worth mentioning that Either is not Java, its Scala or some other library.Edgardoedge
The library is VAVR as mentioned in the title and in the tagScathing
To express that you use java Optional<String>. Optional.isPresent() means there was some error. You don't need an external lib to express that.Windshield
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).Scathing
F
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.

Feola answered 28/8, 2019 at 18:16 Comment(0)
S
0

you can just return null in case of void.

return right(null);
Sedition answered 1/1, 2023 at 11:29 Comment(1)
This is what the other answer suggestedAndrous

© 2022 - 2024 — McMap. All rights reserved.