Scala\'s Option class has an orNull
method, whose signature is shown below.
orNull [A1 >: A](implicit ev : <:<[Null, A1]) : A1
orNull
purpose is first of all in ensuring compatibility of Option
with Java. Though usage of null
is discouraged in Scala, some interfaces may expect to get nullable references.
orNull
has a straightforward implementation:
def orNull[A1 >: A](implicit ev: Null <:< A1): A1 = this getOrElse null
According to this, null
will be returned not only for boxed nulls (Some(null)
), but also for None
(e.g., if you call None.get
, exception will be thrown).
Implicit parameter checks, if the boxed value is nullable.
Good usage example can be found right in the comments to orNull:
val initialText: Option[String] = getInitialText
val textField = new JComponent(initialText.orNull,20)