Re:Overhead of Returning Optional Values in Java and Rust
by thinkharderdev on Saturday October 16, 2021 @02:51PM
(#28890353)
The advantage is if you are explicitly modelling a value that could be empty. You can encode that into the type system by making git an Option<T> instead of just a T (that could be null). At it's most basic level it can just help reduce the possibility of NullPointerExceptions but the real benefit and reduction of boilerplate comes when you use Option as a monad. For instance, in Scala if you have a something like
case class Address(street: String, city: String, state, String)
case class User(id: Int, name: String, address: Option[Address])
case class Address(street: String, city: String, state, String) case class User(id: Int, name: String, address: Option[Address])
def filterCAUsers(users: List[User]): List[User] = users.filter(_.address.exists(_.state != "CA"))