Declare a variable without an initial value

2020-02-28 02:45发布

问题:

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:

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


标签: scala