Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Scala Variables

Scala Variables

A variable is a convenient placeholder used to reference a computer memory address; once created, a variable occupies a certain amount of memory space.

Based on the variable's data type, the operating system allocates memory and decides what will be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or letters in them.

Variable Declaration

Before learning how to declare variables and constants, let's first understand variables and constants.

In Scala, the keyword "var" is used to declare a variable, and the keyword "val" is used to declare a constant.

Immutable variables (val):

Mutable variables (var):

The following is an example of declaring a variable:



var myVar : String = "Foo"

var myVar : String = "Too"

The above defines the variable myVar, which we can modify.

The following is an example of declaring a constant:



val myVal : String = "Foo"

The above defines the constant myVal, which cannot be modified. If the program attempts to modify the value of the constant myVal, it will produce a compile-time error.


Variable type declaration

A variable's type is declared after the variable name and before the equals sign. The syntax for defining a variable's type is as follows:



var VariableName : DataType [=  Initial Value]



或



val VariableName : DataType [=  Initial Value]

Example

object

VariableExample

{

 

def

main

(

args

:

Array

[

String

]

)

:

Unit

=

{

   

// Declare an immutable variable

   

val

immutableVariable

:

Int

=

10

    println

(

s

"Immutable Variable: $immutableVariable"

)

   

// Declare a mutable variable

   

var

mutableVariable

:

Int

=

20

    println

(

s

"Mutable Variable: $mutableVariable"

)

   

// Modify the value of the mutable variable

    mutableVariable

=

30

    println

(

s

"Updated Mutable Variable: $mutableVariable"

)

   

// An immutable variable cannot be reassigned; doing so causes a compile error

   

// immutableVariable = 15 // Uncommenting this line will cause a compilation error

 

}

}

The output of the above code is:

Immutable Variable: 10

Mutable Variable: 20

Updated Mutable Variable: 30


Variable naming conventions

Legal characters:

CamelCase naming:

Avoid single-character variable names:

Meaningful variable names:

Scala-specific naming conventions:


Variable type inference

In Scala, declaring variables and constants does not require specifying a data type; when no data type is specified, the data type is inferred from the variable's or constant's initial value.

Therefore, if you declare a variable or constant without specifying a data type, you must give it an initial value, otherwise an error will occur.

Scala's type inference mechanism can automatically determine a variable's type, so we can omit the type declaration:



val inferredInt = 42  // 编译器推断为 Int

val inferredDouble = 3.14  // 编译器推断为 Double

val inferredString = "Hello, Scala!"  // 编译器推断为 String

val inferredBoolean = true  // 编译器推断为 Boolean

Type inference makes code more concise, but in complex scenarios, explicitly declaring the type can avoid confusion.

When declaring a type explicitly, follow the variable name with a colon and the data type:

val explicitInt: Int = 42

val explicitDouble: Double = 3.14

val explicitString: String = "Hello, Scala!"

val explicitBoolean: Boolean = true

Explicit declarations help improve code readability and maintainability, especially when the type is not easily inferred or is easy to confuse.

Example

object

VariableTypesExample

{

 

def

main

(

args

:

Array

[

String

]

)

:

Unit

=

{

   

// Explicit type declaration

   

val

explicitInt

:

Int

=

42

   

val

explicitDouble

:

Double

=

3.14

   

val

explicitString

:

String

=

"Hello, Scala!"

   

val

explicitBoolean

:

Boolean

=

true

   

// Type inference

   

val

inferredInt

=

42

 

// The compiler infers Int

   

val

inferredDouble

=

3.14

 

// The compiler infers Double

   

val

inferredString

=

"Hello, Scala!"

 

// The compiler infers String

   

val

inferredBoolean

=

true

 

// The compiler infers Boolean

   

// Mutable variable

   

var

mutableInt

:

Int

=

10

    println

(

s

"Initial mutableInt: $mutableInt"

)

    mutableInt

=

20

 

// Modify the variable's value

    println

(

s

"Updated mutableInt: $mutableInt"

)

   

// Output all variables

    println

(

s

"Explicit Int: $explicitInt"

)

    println

(

s

"Explicit Double: $explicitDouble"

)

    println

(

s

"Explicit String: $explicitString"

)

    println

(

s

"Explicit Boolean: $explicitBoolean"

)

    println

(

s

"Inferred Int: $inferredInt"

)

    println

(

s

"Inferred Double: $inferredDouble"

)

    println

(

s

"Inferred String: $inferredString"

)

    println

(

s

"Inferred Boolean: $inferredBoolean"

)

 

}

}

The output of the above code is:

Initial mutableInt: 10

Updated mutableInt: 20

Explicit Int: 42

Explicit Double: 3.14

Explicit String: Hello, Scala!

Explicit Boolean: true

Inferred Int: 42

Inferred Double: 3.14

Inferred String: Hello, Scala!

Inferred Boolean: true


Scala multiple variable declarations

In Scala, you can declare multiple variables at the same time. This not only makes the code more concise, but also ensures the relevance of multiple variables declared on the same line.

In Scala, you can use comma separation, tuple destructuring, and for comprehensions to declare multiple variables at the same time.

You can declare multiple variables on one line using commas:

val xmax, ymax = 100  // xmax, ymax都声明为100

Example

object

MultipleVariables

{

 

def

main

(

args

:

Array

[

String

]

)

:

Unit

=

{

   

// Declare multiple immutable variables at the same time

   

val

a, b, c

:

Int

=

5

    println

(

s

"a: $a, b: $b, c: $c"

)

   

// Declare multiple mutable variables at the same time

   

var

x, y, z

:

Int

=

10

    println

(

s

"x: $x, y: $y, z: $z"

)

   

// Modify the value of the mutable variable

    x

=

20

    y

=

30

    z

=

40

    println

(

s

"Updated x: $x, y: $y, z: $z"

)

 

}

}

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



scala> val pa = (40,"Foo")

pa: (Int, String) = (40,Foo)

Example

object

TupleDestructuring

{

 

def

main

(

args

:

Array

[

String

]

)

:

Unit

=

{

   

// Declare multiple variables at the same time using tuple destructuring

   

val

(

a, b, c

)

=

(

1

,

2

,

"hello"

)

    println

(

s

"a: $a, b: $b, c: $c"

)

   

// Declare multiple mutable variables at the same time using tuple destructuring

   

var

(

x, y, z

)

=

(

10

,

20

,

"world"

)

    println

(

s

"x: $x, y: $y, z: $z"

)

   

// Modify the value of the mutable variable

    x

=

30

    y

=

40

    z

=

"Scala"

    println

(

s

"Updated x: $x, y: $y, z: $z"

)

 

}

}

Declaring multiple variables with for comprehensions

In a for comprehension, you can declare multiple variables at the same time for iteration and generating new collections.

Example

object

ForComprehension

{

 

def

main

(

args

:

Array

[

String

]

)

:

Unit

=

{

   

// Declare multiple variables at the same time for iteration

   

val

numbers

=

List

(

(

1

,

"one"

)

,

(

2

,

"two"

)

,

(

3

,

"three"

)

)

   

for

(

(

number, word

)

<

)

{

println

(

s

"Number: $number, Word: $word"

)

   

}

   

// Generate a new collection using a for comprehension

   

val

newNumbers

=

for

{

     

(

number, word

)

<

}

yield

(

number

2

, word.

toUpperCase

)

    println

(

s

"New Numbers: $newNumbers"

)

 

}

}