Why does the Option or Null method have this extra implicit argument?

I wonder what the reason (implicit ev: Null <:< A1) here:

 sealed abstract class Option[+A] extends Product with Serializable { def orNull[A1 >: A](implicit ev: Null <:< A1): A1 = this getOrElse null ... } 

Would not be

 def orNull[A]: A = this getOrElse null 

enough given that it doesn't even work with value types such as

 Option(1).orNull 

but

 Option(1).getOrElse(null) 

does?

Option source code

+7
source share
2 answers

Not all scala types may be empty. In particular, Any has two children: AnyRef and AnyVal. AnyRef can handle null types. AnyVal types can be primitives on the JVM and therefore cannot be null. Implicit is deferred type checking, which allows Option [String] to use orNull, but not Option [Int].

Note. This dichotomy of an Int object, where the boxed object / primitive / unboxed has very strange manifestations in Scala, such as null.asInstanceOf [Int] == ​​0 // true.

+10
source
 scala> abstract class Op[A] { | def getOrElse(b: A): A | def orNull[A]: A = this getOrElse null | } <console>:14: error: type mismatch; found : Null(null) required: A def orNull[A]: A = this getOrElse null ^ 

So, null not a valid type for all A , only for nulls. AnyVal subclasses are typical examples of types that are not null. In the absence of this parameter, it is not possible to write this method.

+5
source

All Articles