Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala type constraints doesn't allow null

Tags:

types

null

scala

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.

like image 610
Konstantin Solomatov Avatar asked Jun 26 '12 21:06

Konstantin Solomatov


1 Answers

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.

like image 85
Geoff Reedy Avatar answered Oct 22 '22 21:10

Geoff Reedy