I have the following Scala code:
class X[T1 <: AnyRef] {
var _x : T1 = null
}
The code _x = null is highlighted as error:
error: type mismatch;
found : Null(null)
required: T1
var _x : T1 = null : T1
If I add Null type constraint everything works fine. Why this happens? Scala defines AnyRef as equivalent of java.lang.Object, which is of course, nullable.
Instead of
var _x : T1 = null
use
var _x : T1 = _
Explanation from the Scala Language Specification:
A variable definition var x: T = _ can appear only as a member of a template. It introduces a mutable field with type T and a default initial value. The default value depends on the type T as follows:
0 if T is Int or one of its subrange types,
0L if T is Long,
0.0f if T is Float,
0.0d if T is Double,
false if T is Boolean,
() if T is Unit,
null for all other types T.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With