English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Variables in Scala

Eine Variable ist ein bequemes Platzhalter, das verwendet wird, um die Adresse des Computerspeichers zu referenzieren. Nach der Erstellung einer Variable belegt sie einen bestimmten Speicherplatz.

Basierend auf dem datentyp der Variable, führt der Betriebssystem eine Speicherzuweisung durch und entscheidet, was in der reservierten Speicher gespeichert wird. Daher können Sie durch Zuweisung verschiedener datentypen an Variablen Integer, Bruchzahlen oder Buchstaben in diesen Variablen speichern.

Variablen.deklaration

Bevor wir lernen, wie man Variablen und Konstanten deklarieren, sollten wir einige Informationen über Variablen und Konstanten kennen.

  • Ein, Variablen: Eine Variable, deren Wert während des Laufs des Programms möglicherweise geändert wird, wird als Variable bezeichnet. Zum Beispiel: Zeit, Alter.

  • Zwei, Konstanten Eine Variable, deren Wert während des Laufs des Programms nicht geändert wird, wird als Konstante bezeichnet. Zum Beispiel: numerische Werte 3verwendet, das Zeichen 'A'.

In Scala wird das Schlüsselwort "var" Variablen.deklaration, verwenden sie das Schlüsselwort "val" Konstanten.deklaration.

Variablen.deklaration beispiele sind wie folgt:

var myVar : String = "Foo"
var myVar : String = "Too"

The variable myVar defined above can be modified.

Here is an example of declaring a constant:

val myVal: String = "Foo"

The constant myVal defined above is immutable. If the program tries to modify the value of the constant myVal, the program will report an error at compile time.

Variable Type Declaration

The type of a variable is declared before the variable name and after the equal sign. The syntax format for defining the type of a variable is as follows:

var VariableName: DataType [= Initial Value]
or
val VariableName: DataType [= Initial Value]

Variable Type Reference

In Scala, it is not necessary to specify the data type when declaring variables or constants. If the data type is not specified, it is inferred from the initial value of the variable or constant.

Therefore, if a variable or constant is declared without specifying a data type, it must have an initial value; otherwise, an error will occur.

var myVar = 10;
val myVal = "Hello, Scala!"

In the above example, myVar will be inferred as Int type, and myVal will be inferred as String type.

Multiple Variable Declarations in Scala

Scala supports the declaration of multiple variables:

val xmax, ymax = 100  // xmax, ymax are declared as100

If a method returns a tuple, we can use val to declare a tuple:

scala> val pa = (40,"Foo")
pa: (Int, String) = (40,Foo)