Scala type restrictions do not allow

I have the following Scala code:

class X[T1 <: AnyRef] {
   var _x : T1 = null 
}

Code _x = null is highlighted as an error:

error: type mismatch;
found   : Null(null)
required: T1
var _x : T1 = null : T1

If I add a constraint of type Null, everything will work fine. Why is this happening? Scala defines AnyRef as the equivalent of java.lang.Object, which of course is nullable.

+5
source share
4 answers

Instead

var _x : T1 = null

using

var _x : T1 = _

Explanation from Scala Language Specification:

The var x: T = _ variable definition can only be displayed as a member of the template. It introduces a mutable field with type T and an initial default value. The default value depends on type T as follows:

0, T Int ,
0L, T ,
0.0f, T Float,
0.0d, T Double,
false, T ,
(), T - ,
null T.

+10
class X[T1 <: AnyRef] {
   var _x : T1 = null 
}

, , T1 <: AnyRef T1 >: Null.

?

Nothing AnyRef, Nothing .

+6

, NULL, Null:

class X[T1 >: Null] {
   var _x : T1 = null
}
+1

, null Scala . , null. . Option.

-1

All Articles