Skip to content

X extracting values

John McClean edited this page Jul 5, 2018 · 1 revision

Extracting values from Cyclops X types

If you are used to Java's Optional or Scala's Option you may expect to be able to write code like this in Cyclops.

Option<Integer> opt = Option.some(10);

int ten = opt.get(); // No Such Method

One of the design goals in Cyclops X is to make illegal states unrepresentable. In Java this would throw a NullPointerException

Optional<Integer> opt = Optional.empty();
int value = opt.get(); //Exception thrown at Runtime

This is a class of error that we could remove entirely from our code base, if only the API didn't allow us to define the illegal state in code. In Cyclops X we do not expose a get() method on types that may not have an appropriate value.

On Sum types use orElse / orElseGet

Option<Integer> opt = Option.none();
int value = opt.orElse(-1); //-1
Either<String,Integer> strOrInt = Either.left("hello");
int value = strOrInt.orElse(-1); //-1

The orElseGet method allows us to supply a lazily evaluated value

Option<Integer> opt = Option.none();
int value = opt.orElseGet(this::expensiveOperation); 

On Persistent Collections use getOrElse

Using the JDK Collections we can write code like this

List<Integer> list = Arrays.asList();
int value = list.get(10); //throws IndexOutOfBoundsException at Runtime

Cyclops X Persistent Collections prevent these runtime errors from occuring, the get method returns an Option (which contains the value if the index is within range otherwise an Option.none is returned).

ImmutableList<Integer> list = Seq.empty();
Option<Integer> value = list.get(10);

To directly and safely access the value use getOrElse

ImmutableList<Integer> list = Vector.empty();
int value = list.getOrElse(10);

To lazily evaluate an alternative should the index fall out of range use getOrElseGet

ImmutableSet<Integer> set = HashSet.empty();
int value = set.getOrElseGet(this::expensiveOperation);
Clone this wiki locally