Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this the proper way to initialize null references in Scala?

Tags:

null

scala

Let's say I have a MyObject instance which is not initialized:

var a:MyObject = null 

is this the proper way to initialize it to null?

like image 837
Geo Avatar asked Mar 13 '10 21:03

Geo


People also ask

Is using null in Scala a good practice?

As a word of caution (and balance), the Twitter Effective Scala page recommends not overusing Option , and using the Null Object Pattern where it makes sense. As usual, use your own judgment, but try to eliminate all null values using one of these approaches.

How do you handle null values in Scala?

In Scala, using null to represent nullable or missing values is an anti-pattern: use the type Option instead. The type Option ensures that you deal with both the presence and the absence of an element. Thanks to the Option type, you can make your system safer by avoiding nasty NullPointerException s at runtime.

Is there null in Scala?

Nothing - at the bottom of the Scala type hierarchy. Null is the type of the null literal. It is a subtype of every type except those of value classes. Value classes are subclasses of AnyVal, which includes primitive types such as Int, Boolean, and user-defined value classes.

Can we assign null value to reference variable?

In C#, you can assign the null value to any reference variable. The null value simply means that the variable does not refer to an object in memory.


2 Answers

Alternatives

Use null as a last resort. As already mentioned, Option replaces most usages of null. If you using null to implement deferred initialisation of a field with some expensive calculation, you should use a lazy val.

Canonical initialisation to null

That said, Scala does support null. I personally use it in combination with Spring Dependency Injection.

Your code is perfectly valid. However, I suggest that you use var t: T = _ to initialize t to it's default value. If T is a primitive, you get the default specific to the type. Otherwise you get null.

Not only is this more concise, but it is necessary when you don't know in advance what T will be:

scala> class A[T] { var t: T = _ } defined class A  scala> new A[String].t res0: String = null  scala> new A[Object].t             res1: java.lang.Object = null  scala> new A[Int].t    res2: Int = 0  scala> new A[Byte].t res3: Byte = 0  scala> new A[Boolean].t res4: Boolean = false  scala> new A[Any].t    res5: Any = null 

Advanced

Using var t: T= null is a compile error if T is unbounded:

scala> class A[T] { var t: T = null } <console>:5: error: type mismatch;  found   : Null(null)  required: T        class A[T] { var t: T = null } 

You can add an implicit parameter as evidence that T is nullable -- a subtype of AnyRef not a subtype of NotNull This isn't fully baked, even in Scala 2.8, so just consider it a curiousity for now.

scala> class A[T](implicit ev: Null <:< T) { var t: T = null }            defined class A 
like image 118
retronym Avatar answered Oct 10 '22 02:10

retronym


The canonical answer is don't use null. Instead, use an option type:

var a = None : Option[MyObject] 

When you want to set it:

a = Some(foo) 

And when you want to read from it, test for None:

a match {   case None => Console.println("not here")   case Some(value) => Console.println("got: "+value) } 
like image 23
David Crawshaw Avatar answered Oct 10 '22 04:10

David Crawshaw