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 anOption[String], or with aString. If it’s called with aString, then the argument is wrapped inOption.apply().The type of
sisOption[String]. -
foo?.bar()is shorthand forOption(foo).map(_.bar())if foo is not already an Option, otherwise it’sfoo.map(_.bar()).If
bar()returns aString, then the result offoo?.bar()isOption[String].
Advantages:
-
Easier interop with Java null-returning libraries while retaining all of
Option's benefits. -
Shorter & simpler yet (IMHO) clear syntax.
Disadvantages:
-
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.
Precedent:
-
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 tofoo(s: Seq[String]) -
There’s already a mechanism for having default parameters, i.e. making compile-time modifications to the method parameters.
Issues:
-
How do we handle methods in JARs? Is
foo(s: Option[String])identical tofoo(s ?: String), or does there need to be a special annotation included in the compiled code to indicate that it’s?:notOption?Use same / similar mechanism as
foo(s: String*)? -
How will it work with generics where it’s not known at compile time if a type
Tis anOption[U]or something else? What ifT <: 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:a_? ?.foo().
Apologies if this has already been suggested and discarded - couldn’t find anything when searching for it.
