Learn Scala - Booleans, Comparisons

Question Click to View Answer

What does the following code print?

var t: Boolean = true
println(t)

true is printed. The variable t is typed as a boolean and assigned to the value true. Boolean values can only be assigned to true or false.

What does the following code print?

println(10 > 3)

true is printed because 10 is greater than 3.

What does the following code print?

println(5 != 5)

false is printed because 5 is equal to 5.

What does the following code print?

println(true && false)

false is printed. The && operator only returns true if both operands are true. The second operand is false in this example, so false is printed.

What does the following code print?

println(5 < 6 && 10 == 10)

true is printed because both operands evaluate to true. 5 is less than 6 and 10 is equal to 10. The && operator returns true when both operands are true.

What does the following code print?

println(false || true)

true is printed because the second operand is true. The || operator returns true when either of the operands are true.

What does the following code print?

println("frank" || true)

This code throws an error. Certain languages consider treat strings as truthy of falsy in boolean contexts, but Scala doesn't have truthy or falsy values. true and false are the only values that can be used in a boolean context in Scala.

What does the following code print?

println(40.getClass)

int is printed because 40 is an instance of the Int class.

What does the following code print?

println(99.isInstanceOf[Int])

true is printed because 99 is an instance of the Int class.

What does the following code print?

var f = "4.44".toFloat
println(f.getClass)

float is printed. The string "4.44" is first converted to a floating point number and then the class name is printed.

What does the following code print?

println(77.toString == "77")

true is printed. The integer 77 is converted to a string and is equivalent to "77".