2 ms·
Not with a good type system, i.e. a type system which supports algebraic types (or equivalent) and which explicitly disallows null. With such a type system you
by lomnakkus 12y ago
Not with a good type system, i.e. a type system which supports algebraic types (or equivalent) and which explicitly disallows null. With such a type system you wouldn't be able to write the second example as is since string interpolation/concatenation wouldn't be defined for option<string>, only string. You would write something like:
const option<string> maybeEmail = ....
case maybeEmail of
Some email -> system.out.write_line("....{{email}}")
None -> system.out.write_line("Alice doesn't have an email address.")
The thing to notice here is that we're accessing "email" and not "maybeEmail" in the Some case. This guarantees that we cannot get a null value (since the possibility has been eliminated by the case match).
This simple example doesn't do it justice, however. The real benefit comes when you have functions taking option<X> vs. X arguments and/or returning option<X> vs. X. If you get a plain X (either as a return value or parameter) you know that it cannot be null. No such luck in a language which permits "null" as a value for all (reference) values.
Of course algebraic data types go much further than just this. I'd encourage you to look into them in e.g. Haskell or some variant of ML.