top of page
Interesting Recent Posts :
Writer's pictureRohit chopra

Vavr Library In Java: Either Code Example



Introduction: Vavr is a functional programming library for Java that provides immutable collections, functional control structures, and more. One of its most useful features is the Either class, which represents a value that can be one of two types: either a value of type A or a value of type B. This makes it ideal for handling errors in a functional way.

Here's a code example to demonstrate how to use Vavr Either in Java:

Sample Code:


import io.vavr.control.Either;

public class EitherExample {

    public static void main(String[] args) {

        // Example 1: Either as a return typeEither<String, Integer> result = divide(10, 5);

        if (result.isLeft()) {
            System.out.println(result.getLeft());
        } else {
            System.out.println("Result: " + result.get());
        }

        // Example 2: Either as a parameter typeString input = "hello";
        Either<String, Integer> parsed = parseInteger(input);

        if (parsed.isLeft()) {
            System.out.println("Failed to parse: " + parsed.getLeft());
        } else {
            System.out.println("Parsed value: " + parsed.get());
        }

    }

    public static Either<String, Integer> divide(int dividend, int divisor) {
        if (divisor == 0) {
            return Either.left("Cannot divide by zero");
        } else {
            return Either.right(dividend / divisor);
        }
    }

    public static Either<String, Integer> parseInteger(String input) {
        try {
            return Either.right(Integer.parseInt(input));
        } catch (NumberFormatException e) {
            return Either.left("Input is not a valid integer");
        }
    }

}

Sample Output:


Result: 2
Failed to parse: Input is not a valid integer

In this example, we have two methods that return an Either object. The divide method returns an Either object that can contain either a String or an Integer, depending on whether the division was successful or not. The parseInteger method returns an Either object that can contain either a String or an Integer, depending on whether the input string can be parsed as an integer or not.

In the main method, we call these methods and check whether the result is a Left or a Right value using the isLeft() method. If it is a Left value, we print the error message using the getLeft() method. If it is a Right value, we print the result using the get() method.

98 views

Recent Posts

See All

Comments


bottom of page