The value of `A>: Null`?

I tried to write a function that will not compile if null passed:

 $scala Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_101). Type in expressions for evaluation. Or try :help. scala> :t null Null scala> def f[A >: Null](x: A):A = x f: [A >: Null](x: A)A 

However, this did not work as I expected:

 scala> f( null ) res1: Null = null 
+6
source share
3 answers

As already noted, A >: Null allows A be Null itself, but that doesn't even matter. Even if A to be a strict supertype of Null , it would still be possible to pass Null to f , since Null is a valid value for these types (which follows directly from the fact that Null is a subtype of them).

If you do not want to accept types with a null value, A must be a subtype of AnyVal . Note that this will prevent the passing of any value of reference types, not just Null .

Cannot accept reference types without accepting null.

+6
source

Scala Specification Section 3.5.2 (Compliance) (Focus):

The relation <: forms a preliminary order between types, i.e. transitive and reflective . the smallest upper bounds and the largest lower bounds of a set of types are understood relative to this order.

So, if we look at the declaration of a type constructor from a mathematical point of view, we will see the relation :< like:

 Null <: T <: Any 

Since by definition the relation is reflexive, Null <: Null is in the relation, which makes null a valid value to be passed to the method.

As @ sepp2k rightly said in the comments and in his answer that A not limited to an upper bound, means that Any is a valid candidate, which means that null can be passed in any case.

+1
source

A :> B means that A is a supertype of B A >: Null this boundary means that A is a supertype of Null . Null has two supertypes, Any and AnyRef .

In Scala, you can use Option as a good mechanism to avoid using Null .

What do you think about this?

-one
source

Source: https://habr.com/ru/post/1013727/


All Articles