20

This Scala tutorial has the following to say about declaring variables without an initial value:

If you do not assign any initial value to a variable, then it is valid as follows:

var myVar :Int;  
val myVal :String;

But when I try that code in the Scala REPL, I get these errors:

scala> var myVar :Int;
<console>:10: error: only classes can have declared but undefined members
(Note that variables need to be initialized to be defined)
       var myVar :Int;
           ^

scala> val myVal :String;
<console>:10: error: only classes can have declared but undefined members
       val myVal :String;

Why is this? Is the tutorial for an older version of Scala?
I couldn't find a specific version of Scala that the tutorial is written for, but I am running Scala version 2.11.7 on OpenJDK 64bit, Java 1.8.0_66.


  • Is the tutorial outdated, or is the problem with my environment?

  • Is it possible to declare a variable (var or val) without initializing it?

1 Answer 1

41

The error is correct, you can only do that on an abstract class or trait. The tutorial might be assuming that you are writing that code inside of an abstract class.

It is possible to initialize variables to some default value:

var i: Int = _
var s: String = _

But that's essentially the same as:

var i: Int = 0
var s: String = null
Sign up to request clarification or add additional context in comments.

8 Comments

Where are these "defaults" values coming from? Is it dependent on the type? Does the scala compiler define the defaults for basic types like String ?
Answering my own question, I guess that all AnyRef are defaulted to null, and that AnyVal must have their default value defined somehow (still don't see where this happens).
The var i: Int = _ also gives me error: local variables must be initialized
@KiranM What version of scala are you using?
@Alvaro - I am using Scala 2.11.0
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.