How to set uninitialized var fields (field types) in Scala

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is a short recipe, Recipe 4.9, “How to set uninitialize var field types in Scala.”


You want to set the type for an uninitialized var field in a Scala class, so you begin to write code like this:

var x =

and then wonder how to finish writing the expression.

Scala best practices: null values, Option, Some, and None

In his excellent book, Beginning Scala, David Pollak provides a series of statements that can be considered as a recipe for avoiding the use of null values in your Scala code. I've organized his statements here in the following three sections.

1) General rules about null and Option

We begin with the following general rules regarding the use of null values in Scala code:

Ruby NameError: uninitialized constant error message

Problem: When working with some Ruby code in an irb session, I just got the following error message:

NameError: uninitialized constant Tempfile

Here's a snippet of my irb session where this error occurred:

>> tmp = Tempfile.new
NameError: uninitialized constant Tempfile
	from (irb):1


This "NameError: uninitialized constant" looks intimidating, but it's actually not a big deal: I just forgot to require the tempfile package.