Data types in Arrow aim to encapsulate and enforce common programming patterns. An example of this might be requesting a resource that may either succeed with a single data type, or fail. Several common data types are provided by Arrow to enforce patterns:
- Option: Represents the possible absence of data
- Either: Represents an if/else branch in a data flow
- Try: Represents an operation that may result in a success with a single result, or an exception
These data types are implemented as Kotlin data classes, or as sealed classes comprising object classes and data classes. The goal is to enforce these common patterns as well as immutability.
In this snippet, we create an instance of Some, which extends Option, and then map that to another Some instance. We can then use the getOrElse() function to access that value while providing a default value:
val someNumber = Some(1).flatMap { a ->
Some(a + 1)
}.getOrElse { -1 }
Arrow also includes other data types for things such as collections:
- NonEmptyList: A homogeneous, non-empty list
- ListK: A wrapper around Kotlin List that is compatible with Arrow typeclasses
- MapK: A wrapper around Kotlin Map that is compatible with Arrow typeclasses
The following line of code is an example of the NonEmptyList data type:
val nonEmptyList = NonEmptyList.of(1, 2, 3, 4, 5)
Through these data types, Arrow enforces common functional programming patterns and can add/extend functionality through mechanisms such as typeclasses.