java-Quick example for Vavr(2): Use Vavr's tuple in SpringBoot mvc restful controller

-Quick example for Vavr(1): Use Vavr's tuple to return multiple objects from a java method

-Quick example for Vavr(2): Use Vavr's tuple in SpringBoot mvc restful controller

1. The purpose of this post

I would demo how to return multiple result objects from a SpringBoot controller method by using Vavr.

1.1 What is Vavr

According to the Vavr’s website:

Vavr is an object-functional language extension to Java 8, which aims to reduce the lines of code and increase code quality. It provides persistent collections, functional abstractions for error handling, concurrent programming, pattern matching and much more.

Because Vavr does not depend on any libraries (other than the JVM) you can easily add it as standalone .jar to your classpath.

2. Environments

  • java 1.8+
  • Vavr 0.9+

3. How to return multiple objects from a SpringBoot controller method by using Vavr’s Tuple

3.1 Add Vavr dependency to your pom

        <dependency>
            <groupId>io.vavr</groupId>
            <artifactId>vavr</artifactId>
            <version>0.10.0</version>
        </dependency>

You can get vavr latest version from link

3.2 Write the controller

    @RequestMapping(value="/getVavrResult")
    public @ResponseBody
    Tuple2<String,Integer> getVavrResult() {
        return new Tuple2<String, Integer>("test",1);
    }

It’s very simple:

  • We use Tuple2<String,Integer> as the return type of the method
  • We add @ResponseBody to tell spring that we want this object to be serialized to String(Json)
  • We called the new Tuple2<String,Integer>() to initialize the Tuple, because Tuple is immutable, we must initialize it when construt it.

3.3 Run the springboot app

Run the SpringBoot app, and use curl to call the method:

➜  springboot2-mvc git:(master) ✗ curl http://localhost:8080/getVavrResult
{"_1":"test","_2":1}

You can see that the Vavr’s Tuple has been serialized to Json.

4. Summary

Vavr’s Tuple is a good way to encapsulate temporary immutable objects, it’s not necessary to define such objects that only be used once.

To be continued on this topic…