Option Cheat Sheet
Adapted from λ Tony's blog λ scala.Option Cheat Sheet
and_then (aka flatMap in Scala)
match option {
None => None,
Some(x) => foo(x)
}
This code is equivalent to :
option.and_then(foo)
flatten
match option {
None => None,
Some(x) => x
}
This code is equivalent to :
option.flatten() //(and not unwrap() that would fail for option = None)
map
match option {
None => None,
Some(x) => Some(foo(x))
}
This code is equivalent to :
option.map(foo)
for_each
match option {
None => (),
Some(x) => foo(x)
}
This code is equivalent to :
option.into_iter().for_each(foo);
is_some
match option {
None => false,
Some(_) => true
}
This code is equivalent to :
option.is_some()
is_none
match option {
None => true,
Some(_) => false
}
This code is equivalent to :
option.is_none()
all (aka forall in Scala)
match option {
None => true,
Some(x) => foo(x)
}
This code is equivalent to :
option.into_iter().all (|x| foo(x))
any (aka exists in Scala)
match option {
None => false,
Some(x) => foo(x)
}
This code is equivalent to :
option.into_iter().any (|x| foo(x))
or (aka orElse in Scala)
match option {
None => foo,
Some(x) => Some(x)
}
This code is equivalent to :
option.or(foo)
unwrap_or (aka getOrElse in Scala)
match option {
None => foo,
Some(x) => x
}
This code is equivalent to :
option.unwrap_or(foo)
filter_map().collect() (aka toList in Scala)
match option {
None => Vec::new(),
Some(x) => vec![x]
}
This code is equivalent to :
option.into_iter().filter_map(|x| Some(x)).collect::<Vec<_>>()