Learn Scala - Variables, values, and Types

Question Click to View Answer

Use the REPL to print the string "greetings".

println("greetings")

What does the following code print?

var x: Int = 22
println(x)

22 is printed.

The variable x is typed as an integer and assigned to the value 22. After the variable is created, it is printed.

What does the following code print? What is the type of variable y?

var y = 99
println(y)

99 is printed.

The variable y is assigned to the value 99. Since a type is not explicitly set, the type is inferred based on the value. In this case, y is typed as an integer.

Scala is a statically typed language and variables can only have a single type that never changes.

What does the following code print?

var aa: String = "hello"
aa = "pretty"
println(aa)

"pretty" is printed. The variable aa is typed as a string and assigned to the value "hello". aa is then reassigned to the value "pretty".

What does the following code print?

var bb: Int = 10
bb = "funny"
println(bb)

This code throws an error.

The variable bb is typed as an integer and assigned to the value 10. bb cannot be reassigned to the string "funny". bb can only be reassigned to other integers.

What does the following code print?

val cc: Double = 3.14
println(cc)

3.14 is printed. Notice that this example uses the val keyword and does not use the var keyword.

cc is typed as a double (a floating point number) and assigned to 3.14.

What does the following code print?

val dd: Double = 9.99
dd = 10.01
println(dd)

This code throws an error. Variables assigned with the val keyword cannot be reassigned to another value after they've been assigned.

This code would not have errored out if the var keyword was used.

Variables defined with the var keyword can be reassigned.

Variables defined with the val keyword cannot be reassigned.

What is the type of the variable gg?

var gg = 8.88

gg is a double (a floating point number). When gg is assigned, a type is not explicitly set, so the type is inferred based on the value. Scala is smart enough to guess that 8.88 is a floating point value.