So what Options do I have?

Contents
Option types
Option type documentation:
Same names, a bit different API
Scala
In Scala the variants are called: None and Some which are final case subclasses of Option. I’ve noticed the subclassing has the nice property of helping in IDE to discover the variants (which is also the case, for example, for Try subclasses.
Rust
In Rust, the variants are also conveniently named Some and None.
API differences
(Scala vs Rust)
- check presence: isDefined vs is_some
- check absence: isEmpty vs is_none
- transform value: map vs map
- chain options: flatMap vs and_then
- filter value: filter vs filter
- default value: getOrElse vs unwrap_or
- lazy default: getOrElse vs unwrap_or_else
- alternative: orElse: vs or
- to collection: toList vs iter
- unsafe extract: get vs unwrap
Some specifics
- Scala has some functions that
- does not make sense in Rust but has when interop with Java is required (orNull - Rust has no null by design)
- convert to Either subtypes (toLeft, toRight)
- Rust has functions
- to convert between reference types (as_ref, as_mut, as_deref)
- to modify in place or work with ownership (take, replace)
- to transform to Result (ok_or, transpose)
Exercise
This is the example from Rust module option docs:
|
|
Let’s see how it would look like in scala:
|
|
My notes:
- in scala 2.x (before enum and named tuples) modelling two similar variants is possible either by
- overriding
abstract class Kingdomin case subclasses (would preserve class hierarchy) or - scoping
case class Plantandcase class Animalinobject Kingdomwhich allows, well, scope access (which I like very much - this approach pushes towards providing explicit path to a class)
- overriding
- forEach allows to pattern match in anonymous function - without defining any binding to a iteration variable (big_thing in Rust snippet)
- scala requires to declare a type of
nameOfTheBiggestAnimal- without it the code does not compile; that’s becauseNonevalue resolves toNone.typeand Some[String] is expected in assignment: compiler cries until I fixed that:

That’s all for today.
Happy coding!