Please explain use of Option's orNull method

后端 未结 5 759
北荒
北荒 2021-02-01 21:29

Scala\'s Option class has an orNull method, whose signature is shown below.

orNull [A1 >: A](implicit ev : <:<[Null, A1]) : A1
5条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-01 21:40

    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)
    

提交回复
热议问题