Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare a variable without an initial value

Tags:

scala

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?

like image 487
Matt C Avatar asked May 11 '16 23:05

Matt C


People also ask

Can you declare a variable without initializing?

Declaring a Variable Without InitializingWe can use the let keyword. We use the let keyword when variables are mutable. That means we can change or set the value later on in the program.

Can you declare a variable without giving it a value?

He says that it's also possible to declare a variable without giving it an initial value and also that we must be careful not to use a variable which has been declared without an initial value and that has not been assigned a value.

How do you declare an empty variable?

In order to define a null variable, you can use the None keyword. Note: The None keyword refers to a variable or object that is empty or has no value. It is Python's way of defining null values.

When a variable is declared without initialization which value is assigned to it?

The default value of variables that do not have any value is undefined. You can assign a value to a variable using the = operator when you declare it or after the declaration and before accessing it. In the above example, the msg variable is declared first and then assigned a string value in the next statement.


1 Answers

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
like image 188
Alvaro Carrasco Avatar answered Oct 04 '22 20:10

Alvaro Carrasco