java-Quick example for Vavr(1): Use Vavr's tuple to return multiple objects from a java method
1. The purpose of this post
I would demo how to return multiple result objects from a java 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 java method
3.1 The old way
If we want to return a result that contains three objects , we can define a result object like this:
And then we return it in the method like this:
Then, we consume the result like this:
Run the code, we get this:
3.2 The Vavr way
3.2.1 Add Vavr dependency to your pom
You can get vavr latest version from link
3.2.2 Use the Tuple from Vavr
Tuples are immutable and can hold multiple objects of different types in a type-safe manner.
Let’s redefine the getResults by using vavr’s tuple:
It’s very simple:
- You can see that we use Tuple3, that means this tuple contains three objects, Tuple1 means only one objects in the tuple
- Because Tuple is immutable, so you should use the constructor to build the Tuple, not by setters.
Then we use the Tuple result and print it:
You can see that:
- We use the Tuple’s _1,_2,_3 to access the objects stored in the Tuple, it’s very simple
- Instead of using _1 to access objects, you can also use _1() to access the number one object stored in the Tuple
Run the code, we get this:
It’s just the same as the old way.
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…