Learn Scala - Expressions, Conditionals

Question Click to View Answer

What does the following code print?

var number = {val x = 2 * 2; x + 40}
println(number)

44 is printed. The code that's enclosed in the brackets {} is called an expression. Expressions are a unit of code that return a value after they're executed.

x is a local variable in the expression. The last statement in the expression x + 40 is returned.

What does the following code print?

var ttt = {
  var first = "katy"
  s"$first perry"
}
println(ttt)

katy perry is printed. ttt is an example of a multiline expression. The last line of a multiline expression is returned.

What does the following code print?

var source = "hotline"
var badSong = {
  s"$source bling"
}
println(badSong)

hotline bling is printed. Variables defined outside of an expression can be accessed within the expression.

What does the following code print?

var band = {
  var name = "sublime"
  name
}
println(name)

This code raises an error. Variables defined within an expression are local to the expression and cannot be accessed outside the expression.

What does the following code print?

if (10 > 2) { println("ten is greater than two") }

This code prints ten is greater than two. The boolean condition 10 > 2 evaluates to true so the expression after the if statement is executed.

What does the following code print?

if (10 > 2) println("ten is greater than two")

This code prints ten is greater than two. This example is very similar to the previous example but the brackets {} surrounding the expression are omitted.

What does the following code print?

if (5 != 5) println("not equal") else println("they're equal!")

they're equal! is printed. If/else statements can be constructed on a single line so a ternary operator is not needed with Scala.

What does the following code print?

if (true) {
  "it is true"
} else {
  "i'm confused"
}

it is true is printed. Multiline if/else statements are much more readable in my opinion.