Introduction to Vavr – Vavr简介

最后修改: 2016年 12月 29日


1. Overview


In this article, we are going to explore exactly what Vavr is, why we need it and how to use it in our projects.


Vavr is a functional library for Java 8+ that provides immutable data types and functional control structures.

Vavr是一个用于Java 8+的功能库,提供不可变的数据类型和功能控制结构。

1.1. Maven Dependency


In order to use Vavr, you need to add the dependency:



It is recommended to always use the latest version. You can get it by following this link.


2. Option


The main goal of Option is to eliminate null checks in our code by leveraging the Java type system.


Option is an object container in Vavr with a similar end goal like Optional in Java 8. Vavr’s Option implements Serializable, Iterable, and has a richer API.

Option是Vavr中的一个对象容器,其最终目标与Java 8中的Optional相似。Vavr的Option实现了Serializable,Iterable,并拥有更丰富的API

Since any object reference in Java can have a null value, we usually have to check for nullity with if statements before using it. These checks make the code robust and stable:


public void givenValue_whenNullCheckNeeded_thenCorrect() {
    Object possibleNullObj = null;
    if (possibleNullObj == null) {
        possibleNullObj = "someDefaultValue";

Without checks, the application can crash due to a simple NPE:


@Test(expected = NullPointerException.class)
public void givenValue_whenNullCheckNeeded_thenCorrect2() {
    Object possibleNullObj = null;
    assertEquals("somevalue", possibleNullObj.toString());

However, the checks make the code verbose and not so readable, especially when the if statements end up being nested multiple times.


Option solves this problem by totally eliminating nulls and replacing them with a valid object reference for each possible scenario.


With Option a null value will evaluate to an instance of None, while a non-null value will evaluate to an instance of Some:


public void givenValue_whenCreatesOption_thenCorrect() {
    Option<Object> noneOption = Option.of(null);
    Option<Object> someOption = Option.of("val");

    assertEquals("None", noneOption.toString());
    assertEquals("Some(val)", someOption.toString());

Therefore, instead of using object values directly, it’s advisable to wrap them inside an Option instance as shown above.


Notice, that we did not have to do a check before calling toString yet we did not have to deal with a NullPointerException as we had done before. Option’s toString returns us meaningful values in each call.


In the second snippet of this section, we needed a null check, in which we would assign a default value to the variable, before attempting to use it. Option can deal with this in a single line, even if there is a null:


public void givenNull_whenCreatesOption_thenCorrect() {
    String name = null;
    Option<String> nameOption = Option.of(name);
    assertEquals("baeldung", nameOption.getOrElse("baeldung"));

Or a non-null:


public void givenNonNull_whenCreatesOption_thenCorrect() {
    String name = "baeldung";
    Option<String> nameOption = Option.of(name);

    assertEquals("baeldung", nameOption.getOrElse("notbaeldung"));

Notice how, without null checks, we can get a value or return a default in a single line.


3. Tuple


There is no direct equivalent of a tuple data structure in Java. A tuple is a common concept in functional programming languages. Tuples are immutable and can hold multiple objects of different types in a type-safe manner.


Vavr brings tuples to Java 8. Tuples are of type Tuple1, Tuple2 to Tuple8 depending on the number of elements they are to take.

Vavr为Java 8带来了图元。图元的类型是Tuple1, Tuple2Tuple8,这取决于它们的元素数量。

There is currently an upper limit of eight elements. We access elements of a tuple like tuple._n where n is similar to the notion of an index in arrays:


public void whenCreatesTuple_thenCorrect1() {
    Tuple2<String, Integer> java8 = Tuple.of("Java", 8);
    String element1 = java8._1;
    int element2 = java8._2();

    assertEquals("Java", element1);
    assertEquals(8, element2);

Notice that the first element is retrieved with n==1. So a tuple does not use a zero base like an array. The types of the elements that will be stored in the tuple must be declared in its type declaration as shown above and below:


public void whenCreatesTuple_thenCorrect2() {
    Tuple3<String, Integer, Double> java8 = Tuple.of("Java", 8, 1.8);
    String element1 = java8._1;
    int element2 = java8._2();
    double element3 = java8._3();
    assertEquals("Java", element1);
    assertEquals(8, element2);
    assertEquals(1.8, element3, 0.1);

A tuple’s place is in storing a fixed group of objects of any type that are better processed as a unit and can be passed around. A more obvious use case is returning more than one object from a function or a method in Java.


4. Try


In Vavr, Try is a container for a computation which may result in an exception.

在Vavr中,Try是一个计算的容器 它可能导致一个异常。

As Option wraps a nullable object so that we don’t have to explicitly take care of nulls with if checks, Try wraps a computation so that we don’t have to explicitly take care of exceptions with try-catch blocks.


Take the following code for example:


@Test(expected = ArithmeticException.class)
public void givenBadCode_whenThrowsException_thenCorrect() {
    int i = 1 / 0;

Without try-catch blocks, the application would crash. In order to avoid this, you would need to wrap the statement in a try-catch block. With Vavr, we can wrap the same code in a Try instance and get a result:


public void givenBadCode_whenTryHandles_thenCorrect() {
    Try<Integer> result = Try.of(() -> 1 / 0);


Whether the computation was successful or not can then be inspected by choice at any point in the code.


In the above snippet, we have chosen to simply check for success or failure. We can also choose to return a default value:


public void givenBadCode_whenTryHandles_thenCorrect2() {
    Try<Integer> computation = Try.of(() -> 1 / 0);
    int errorSentinel = result.getOrElse(-1);

    assertEquals(-1, errorSentinel);

Or even to explicitly throw an exception of our choice:


@Test(expected = ArithmeticException.class)
public void givenBadCode_whenTryHandles_thenCorrect3() {
    Try<Integer> result = Try.of(() -> 1 / 0);

In all the above cases, we have control over what happens after the computation, thanks to Vavr’s Try.


5. Functional Interfaces


With the arrival of Java 8, functional interfaces are inbuilt and easier to use, especially when combined with lambdas.

随着Java 8的到来,functional interfaces被内置并更容易使用,特别是与lambdas结合使用时。

However, Java 8 provides only two basic functions. One takes only a single parameter and produces a result:

然而,Java 8只提供了两个基本函数。一个只接受一个参数并产生一个结果。

public void givenJava8Function_whenWorks_thenCorrect() {
    Function<Integer, Integer> square = (num) -> num * num;
    int result = square.apply(2);

    assertEquals(4, result);

The second only takes two parameters and produces a result:


public void givenJava8BiFunction_whenWorks_thenCorrect() {
    BiFunction<Integer, Integer, Integer> sum = 
      (num1, num2) -> num1 + num2;
    int result = sum.apply(5, 7);

    assertEquals(12, result);

On the flip side, Vavr extends the idea of functional interfaces in Java further by supporting up to a maximum of eight parameters and spicing up the API with methods for memoization, composition, and currying.


Just like tuples, these functional interfaces are named according to the number of parameters they take: Function0, Function1, Function2 etc. With Vavr, we would have written the above two functions like this:

就像图元一样,这些函数接口是根据它们的参数数量来命名的。Function0, Function1, Function2等等。在Vavr中,我们会把上述两个函数写成这样。

public void givenVavrFunction_whenWorks_thenCorrect() {
    Function1<Integer, Integer> square = (num) -> num * num;
    int result = square.apply(2);

    assertEquals(4, result);

and this:


public void givenVavrBiFunction_whenWorks_thenCorrect() {
    Function2<Integer, Integer, Integer> sum = 
      (num1, num2) -> num1 + num2;
    int result = sum.apply(5, 7);

    assertEquals(12, result);

When there is no parameter but we still need an output, in Java 8 we would need to use a Supplier type, in Vavr Function0 is there to help:

当没有参数但我们仍然需要输出时,在Java 8中,我们需要使用Supplier 类型,在Vavr中,Function0是用来帮助的。

public void whenCreatesFunction_thenCorrect0() {
    Function0<String> getClazzName = () -> this.getClass().getName();
    String clazzName = getClazzName.apply();

    assertEquals("com.baeldung.vavr.VavrTest", clazzName);

How about a five parameter function, it’s just a matter of using Function5:


public void whenCreatesFunction_thenCorrect5() {
    Function5<String, String, String, String, String, String> concat = 
      (a, b, c, d, e) -> a + b + c + d + e;
    String finalString = concat.apply(
      "Hello ", "world", "! ", "Learn ", "Vavr");

    assertEquals("Hello world! Learn Vavr", finalString);

We can also combine the static factory method FunctionN.of for any of the functions to create a Vavr function from a method reference. Like if we have the following sum method:


public int sum(int a, int b) {
    return a + b;

We can create a function out of it like this:


public void whenCreatesFunctionFromMethodRef_thenCorrect() {
    Function2<Integer, Integer, Integer> sum = Function2.of(this::sum);
    int summed = sum.apply(5, 6);

    assertEquals(11, summed);

6. Collections


The Vavr team has put a lot of effort in designing a new collections API that meets the requirements of functional programming i.e. persistence, immutability.


Java collections are mutable, making them a great source of program failure, especially in the presence of concurrency. The Collection interface provides methods such as this:


interface Collection<E> {
    void clear();

This method removes all elements in a collection(producing a side-effect) and returns nothing. Classes such as ConcurrentHashMap were created to deal with the already created problems.


Such a class does not only add zero marginal benefits but also degrades the performance of the class whose loopholes it is trying to fill.


With immutability, we get thread-safety for free: no need to write new classes to deal with a problem that should not be there in the first place.


Other existing tactics to add immutability to collections in Java still create more problems, namely, exceptions:


@Test(expected = UnsupportedOperationException.class)
public void whenImmutableCollectionThrows_thenCorrect() {
    java.util.List<String> wordList = Arrays.asList("abracadabra");
    java.util.List<String> list = Collections.unmodifiableList(wordList);

All the above problems are non-existent in Vavr collections.


To create a list in Vavr:


public void whenCreatesVavrList_thenCorrect() {
    List<Integer> intList = List.of(1, 2, 3);

    assertEquals(3, intList.length());
    assertEquals(new Integer(1), intList.get(0));
    assertEquals(new Integer(2), intList.get(1));
    assertEquals(new Integer(3), intList.get(2));

APIs are also available to perform computations on the list in place:


public void whenSumsVavrList_thenCorrect() {
    int sum = List.of(1, 2, 3).sum().intValue();

    assertEquals(6, sum);

Vavr collections offer most of the common classes found in the Java Collections Framework and actually, all features are implemented.


The takeaway is immutability, removal of void return types and side-effect producing APIs, a richer set of functions to operate on the underlying elements, very short, robust and compact code compared to Java’s collection operations.


A full coverage of Vavr collections is beyond the scope of this article.


7. Validation


Vavr brings the concept of Applicative Functor to Java from the functional programming world. In the simplest of terms, an Applicative Functor enables us to perform a sequence of actions while accumulating the results.


The class vavr.control.Validation facilitates the accumulation of errors. Remember that, usually, a program terminates as soon as an error is encountered.


However, Validation continues processing and accumulating the errors for the program to act on them as a batch.


Consider that we are registering users by name and age and we want to take all input first and decide whether to create a Person instance or return a list of errors. Here is our Person class:


public class Person {
    private String name;
    private int age;

    // standard constructors, setters and getters, toString

Next, we create a class called PersonValidator. Each field will be validated by one method and another method can be used to combine all the results into one Validation instance:


class PersonValidator {
    String NAME_ERR = "Invalid characters in name: ";
    String AGE_ERR = "Age must be at least 0";

    public Validation<Seq<String>, Person> validatePerson(
      String name, int age) {
        return Validation.combine(
          validateName(name), validateAge(age)).ap(Person::new);

    private Validation<String, String> validateName(String name) {
        String invalidChars = name.replaceAll("[a-zA-Z ]", "");
        return invalidChars.isEmpty() ? 
            : Validation.invalid(NAME_ERR + invalidChars);

    private Validation<String, Integer> validateAge(int age) {
        return age < 0 ? Validation.invalid(AGE_ERR)
          : Validation.valid(age);

The rule for age is that it should be an integer greater than 0 and the rule for name is that it should contain no special characters:


public void whenValidationWorks_thenCorrect() {
    PersonValidator personValidator = new PersonValidator();

    Validation<List<String>, Person> valid = 
      personValidator.validatePerson("John Doe", 30);

    Validation<List<String>, Person> invalid = 
      personValidator.validatePerson("John? Doe!4", -1);

      "Valid(Person [name=John Doe, age=30])", 

      "Invalid(List(Invalid characters in name: ?!4, 
        Age must be at least 0))", 

A valid value is contained in a Validation.Valid instance, a list of validation errors is contained in a Validation.Invalid instance. So any validation method must return one of the two.


Inside Validation.Valid is an instance of Person while inside Validation.Invalid is a list of errors.


8. Lazy


Lazy is a container which represents a value computed lazily i.e. computation is deferred until the result is required. Furthermore, the evaluated value is cached or memoized and returned again and again each time it is needed without repeating the computation:


public void givenFunction_whenEvaluatesWithLazy_thenCorrect() {
    Lazy<Double> lazy = Lazy.of(Math::random);
    double val1 = lazy.get();
    double val2 = lazy.get();
    assertEquals(val1, val2, 0.1);

In the above example, the function we are evaluating is Math.random. Notice that, in the second line, we check the value and realize that the function has not yet been executed. This is because we still haven’t shown interest in the return value.


In the third line of code, we show interest in the computation value by calling Lazy.get. At this point, the function executes and Lazy.evaluated returns true.


We also go ahead and confirm the memoization bit of Lazy by attempting to get the value again. If the function we provided was executed again, we would definitely receive a different random number.


However, Lazy again lazily returns the initially computed value as the final assertion confirms.


9. Pattern Matching


Pattern matching is a native concept in almost all functional programming languages. There is no such thing in Java for now.


Instead, whenever we want to perform a computation or return a value based on the input we receive, we use multiple if statements to resolve the right code to execute:


public void whenIfWorksAsMatcher_thenCorrect() {
    int input = 3;
    String output;
    if (input == 0) {
        output = "zero";
    if (input == 1) {
        output = "one";
    if (input == 2) {
        output = "two";
    if (input == 3) {
        output = "three";
    else {
        output = "unknown";

    assertEquals("three", output);

We can suddenly see the code spanning multiple lines while just checking three cases. Each check is taking up three lines of code. What if we had to check up to a hundred cases, those would be about 300 lines, not nice!


Another alternative is using a switch statement:


public void whenSwitchWorksAsMatcher_thenCorrect() {
    int input = 2;
    String output;
    switch (input) {
    case 0:
        output = "zero";
    case 1:
        output = "one";
    case 2:
        output = "two";
    case 3:
        output = "three";
        output = "unknown";

    assertEquals("two", output);

Not any better. We are still averaging 3 lines per check. A lot of confusion and potential for bugs. Forgetting a break clause is not an issue at compile time but can result in hard-to-detect bugs later on.


In Vavr, we replace the entire switch block with a Match method. Each case or if statement is replaced by a Case method invocation.


Finally, atomic patterns like $() replace the condition which then evaluates an expression or value. We also provide this as the second parameter to Case:


public void whenMatchworks_thenCorrect() {
    int input = 2;
    String output = Match(input).of(
      Case($(1), "one"), 
      Case($(2), "two"), 
      Case($(3), "three"),
      Case($(), "?"));
    assertEquals("two", output);

Notice how compact the code is, averaging only one line per check. The pattern matching API is way more powerful than this and can do more complex stuff.


For example, we can replace the atomic expressions with a predicate. Imagine we are parsing a console command for help and version flags:


    Case($(isIn("-h", "--help")), o -> run(this::displayHelp)),
    Case($(isIn("-v", "--version")), o -> run(this::displayVersion)),
    Case($(), o -> run(() -> {
        throw new IllegalArgumentException(arg);

Some users may be more familiar with the shorthand version (-v) while others, with the full version (–version). A good designer must consider all these cases.


Without the need for several if statements, we have taken care of multiple conditions. We will learn more about predicates, multiple conditions, and side-effects in pattern matching in a separate article.


10. Conclusion


In this article, we have introduced Vavr, the popular functional programming library for Java 8. We have tackled the major features that we can quickly adapt to improve our code.

在这篇文章中,我们介绍了Vavr,这个流行的Java 8函数式编程库。我们已经解决了一些主要的功能,我们可以快速适应这些功能来改进我们的代码。

The full source code for this article is available in the Github project.