Option[T] is a great & principled way of handling missing / null values. However, it can be syntactically quite verbose.
Inspired by other languages that have chosen a
foo(s ?: String) approach in favor of
foo(s: Option[String]), how about introducing a little bit of syntactic sugar to smoothen the use of Option:
def foo(s ?: String)can be called with either an
Option[String], or with a
String. If it’s called with a
String, then the argument is wrapped in
The type of
foo?.bar()is shorthand for
Option(foo).map(_.bar())if foo is not already an Option, otherwise it’s
String, then the result of
Easier interop with Java null-returning libraries while retaining all of
Shorter & simpler yet (IMHO) clear syntax.
May lead to culture wars about the most principled / correct way of doing things.
May exacerbate operator overloading write-once-never-understand-again line noise.
There’s already special syntax for having an arbitrary number of parameters passed to a function that leads to a non-shown type being used:
foo(s: String*)type erasing to
There’s already a mechanism for having default parameters, i.e. making compile-time modifications to the method parameters.
How do we handle methods in JARs? Is
foo(s: Option[String])identical to
foo(s ?: String), or does there need to be a special annotation included in the compiled code to indicate that it’s
Use same / similar mechanism as
How will it work with generics where it’s not known at compile time if a type
Option[U]or something else? What if
T <: Option[String]?
It’s possible to name a variable
a_?, which would be somewhat confusing when mixed with this syntax, and force the introduction of separating whitespace:
Apologies if this has already been suggested and discarded - couldn’t find anything when searching for it.