-
Notifications
You must be signed in to change notification settings - Fork 4
Either
The concept of Either is to represent a value of one of two possible types.
Instances of Either are either an instance of Left or Right.
This is what is called a disjoint union, meaning that the Either will never contain both types only one of them.
The use case could be to supply a response that could be of either two types or equally an argument to a method that could be of either two types.
In contrast to Try and Option the Either cannot directly be used as a collection (i.e iterate over it). This is due to that Either is unbiased as to which of Left, Right it represents.
To get access to the data represented by the Either you as a programmer have to decide to work with either the Left or Right side. More on this in the examples.
The examples provided on this Wiki are only a subset of the full functionality.
For a complete set of functionality and examples refer to the Java Doc
Either<InputStream, String> either = new Left<>(new FileInputStream("/foo.bar"));
Either<InputStream, String> either = new Right<>("Right is not Left");
Consider the Either in the example:
Either<InputStream, String> either = ...
To get hold of the data it represents you need to decide which side (Left, Right) to work with.
Easiest way is to first decide which side the instance represents.
The methods isLeft() and isRight() will help you decide which side is represented.
Invoking either left() or right() will yield a biased projection for that side.
E.g.
RightProjection<InputStream, String> rp = either.right();
This projection works on the assumption that the data should be of type Right. The projection is an Iterable as well as acting as a collection providing a multitude of methods such as filter(), forEach(), forAll(), get(), getOrElse(), orNull(), asOption(), map() , ...
Now with the projection you can get hold of the data.
E.g.
String s = rp.get();
- Introduction
- JavaDoc (Latest)
- Containers
- Option/Some/None
- Try/Success/Failure
- Either/Left/Right
- Asynchronous Execution
- Future/Promise
- Companion Classes
- The Unit Type
- Testing/Asserts
- License
- Chat room for the project:
- Continuous Integration: