Create Option factory method for T | Null
See original GitHub issueWhen using -Yexplicit-nulls
, it’s often desirable to create an Option
from an obtained reference that might be null
:
For example, the following would avoid any mention of the dreaded null
value:
Option(someJavaMethodPossiblyReturningNull()) match
// Function returned null
case None => // etc.
// Value was non-null.
case Some(x) => // etc.
Except that there is no such factory method, and the Scala compiler complains that it received a T | Null
value when trying to create the Option
value. Clearly, if the nn
method is used to get the type right, then an exception is thrown if the reference is null
.
This use of Option
is idiomatic for handling possibly-null
values, so it seems ironic that it isn’t available when using explicit nulls.
Would it be possible to add a factory method to the Option
companion, such as the following?
object Option:
def apply[T](value: T | Null): Option[T] = // ...
Or am I missing something, such as extension method like nn
that converts the value to an option?
Issue Analytics
- State:
- Created a year ago
- Comments:10 (6 by maintainers)
Top GitHub Comments
A lunch discussion suggested that an explicit
toOption
extension method onT | Null
is a likely good candidate.Why not a simply
getOrElse
extension method?Something like this:
For Strings this also could be helpful (I use for exception messages for example):