Skip to content

Create Option factory method for T | Null #15891

Open
@Facsimiler

Description

@Facsimiler

When 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?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions