Comparisons of Java’s Optional and Scala’s Option

As a brief note today, here are a couple of comparisons of Java’s Optional and Scala’s Option.

First, here’s a Scala makeInt method written with Option in Scala 3:

def makeInt(s: String): Option[Int] = 
    try
        Some(s.toInt)
    catch
        case e: NumberFormatException => None

and here’s the same method written with Optional in Java:

public Optional<Integer> makeInt(String s) {
    try {
        Optional.of(Integer.parseInt(s));
    } catch (NumberFormatException nfe) {
        Optional.empty();
    }
}

Next, these two examples show how similar Option and Optional are when calling a filter and “find” method on either a Java or Scala collection class:

// java
Optional<String> as = strings.filter(s -> s.startsWith("a")).findFirst();
// scala
val as: Option[Int] = strings.filter(_.startsWith("a")).find

As a parting note, Scala also provides some conversion objects/methods that let you convert between Optional and Option when using Java and Scala code in the same project. You can learn more about those by starting at this OptionConverters page.