Vavr: Turns JAVA upside down – Part 1

vavr

The Vavr library, formerly known as Javaslang, is a functional library for Java that provides immutable data types and functional control structures.

Javaslang-Logo

Maven Dependency

Include maven dependency to use VAVR in your project. Ensure that version of Java is 1.8 minimum.

Now, let’s take an overview of features that VAVR library provides where JAVA lacks.

LIST

A List is an eagerly-evaluated sequence of elements. Lists are formed recursively from a head and a tail:

  • Head – the first element
  • Tail – a list containing remaining elements (that list is also formed from a head and a tail)

There are static factory methods in the List API that can be used for creating a List. We can use the static of( ) method to create an instance of List from one or more objects.

We can also use the static empty( ) to create an empty List and ofAll( ) to create a List from an Iterable type:

OPTION

Option is a monadic container type which represents an optional value. Instances of Option are either an instance of Some or the None. Option is tightly integrated with Vavr’s Value and Iterable types. This allows for a very consistent API. You can basically treat an Option like a collection with zero or one element.

You can easily combine it with Vavr’s Try monad, that helps to deal with exceptions in a functional way. Take the following example.

We Try to load a Configuration and convert the result to Option. If an exception is thrown, then the result is None otherwise it is Some.

HANDLING EXCEPTIONS WITH TRY

Vavr library gives us a special container that represents a computation that may either result in an exception or complete successfully. Instances of Try, are either an instance of Success or Failure. 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:

LAZY

Lazy is a monadic container type which represents a lazy evaluated value. The evaluated value is cached or memoized and returned again and again each time it is needed without repeating the computation:

Hope you liked the blog. Stay Tuned and Don’t miss the 2nd part 😉 !!

References


knoldus-advt-sticker


 

Written by 

Charmy is a Software Consultant having experience of more than 1.5 years. She is familiar with Object Oriented Programming Paradigms and has familiarity with Technical languages such as Scala, Lagom, Java, Apache Solr, Apache Spark, Apache Kafka, Apigee. She is always eager to learn new concepts in order to expand her horizon. Her hobbies include playing guitar and Sketching.

Leave a Reply

%d bloggers like this: