Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Quiz

Question 1: Basic try-catch Usage

Consider the following Scala code snippet demonstrating basic usage of try-catch:

try {
  val result = 10 / 0
  println(result)
} catch {
  case e: ArithmeticException => println("Cannot divide by zero.")
} finally {
  println("Operation attempted.")
}

What is the output of this code?

A) Cannot divide by zero.
Operation attempted.
B) Operation attempted.
C) 10 / 0
Operation attempted.
D) Compilation error

Question 2: Catching Multiple Exceptions

Analyze the Scala code snippet below that catches multiple types of exceptions:

try {
  val arr = Array(1, 2, 3)
  println(arr(10))
} catch {
  case e: ArithmeticException => println("Arithmetic exception caught.")
  case e: ArrayIndexOutOfBoundsException => println("Array index out of bounds.")
} finally {
  println("Search attempted.")
}

What does this code print?

A) Arithmetic exception caught.
Search attempted.
B) Array index out of bounds.
Search attempted.
C) Search attempted.
D) Compilation error

Question 3: Using try-catch with a Return Value

Review the Scala code snippet involving try-catch with a return value:

def safeDivide(a: Int, b: Int): String = {
  try {
    val result = a / b
    s"Result: $result"
  } catch {
    case e: ArithmeticException => "Error: Division by zero."
  } finally {
    println("Division operation processed.")
  }
}

println(safeDivide(10, 0))
println(safeDivide(10, 5))

What is the output of this program?

A) Division operation processed.
Error: Division by zero.
Division operation processed.
Result: 2
B) Error: Division by zero.
Result: 2
C) Division operation processed.
Division operation processed.
D) Compilation error

Question 4: Using Option for Safe Value Access

Consider the following Scala code snippet demonstrating the use of Option to safely handle potentially missing values:

def safeFindFirstChar(str: String): Option[Char] = {
  if (str.isEmpty) None
  else Some(str.charAt(0))
}

val charA = safeFindFirstChar("apple")
println(charA)

val charB = safeFindFirstChar("")
println(charB)

What is the output of this code?

A) Some(a)
None
B) a
None
C) Some(a)
""
D) None of the above

Question 5: Handling Multiple Errors with Either

Analyze the Scala code snippet below that uses Either to handle multiple types of errors:

def divide(x: Int, y: Int): Either[String, Int] = {
  if (y == 0) Left("Cannot divide by zero.")
  else Right(x / y)
}

val result1 = divide(10, 2)
println(result1)

val result2 = divide(10, 0)
println(result2)

What does this code print?

A) Right(5)
Left("Cannot divide by zero.")
B) 5
Cannot divide by zero.
C) Right(5)
Right("Cannot divide by zero.")
D) None of the above

Question 6: Graceful Error Handling with Try

Review the Scala code snippet involving Try for graceful error handling:

import scala.util.{Try, Success, Failure}

def toInt(s: String): Try[Int] = Try(s.toInt)

val num1 = toInt("100")
println(num1)

val num2 = toInt("abc")
println(num2)

What is the output of this program?

A) Success(100)
Failure(java.lang.NumberFormatException)
B) 100
Error
C) Success(100)
Failure
D) None of the above

Question 7: Combining Option Values with flatMap

Consider the following Scala code snippet that demonstrates combining Option values using flatMap:

def parsePositiveInt(str: String): Option[Int] = {
  val i = Try(str.toInt).toOption
  i.flatMap { case x if x > 0 => Some(x) case _ => None }
}

val numA = parsePositiveInt("5")
println(numA)

val numB = parsePositiveInt("-5")
println(numB)

What does this code print?

A) Some(5)
None
B) 5
-5
C) Some(5)
Some(-5)
D) None of the above

Question 8: Using for-comprehension with Option

Analyze the Scala code snippet for using for-comprehension to chain operations on Option values:

def findPerson(id: Int): Option[String] = Some("John Doe")
def findAge(person: String): Option[Int] = Some(30)

val personAge = for {
  person <- findPerson(1)
  age <- findAge(person)
} yield age

println(personAge)

What is the output of this code?

A) Some(30)
B) 30
C) None
D) None of the above

Question 9: Safely Accessing Potentially Null Objects

Consider the following Scala code snippet demonstrating a safe way to access potentially null objects:

case class User(name: String, age: Option[Int])

def getUserAge(user: User): String = {
  user.age match {
    case Some(age) => s"User age: $age"
    case None => "Age not provided"
  }
}

val userWithAge = User("Alice", Some(30))
println(getUserAge(userWithAge))

val userWithoutAge = User("Bob", None)
println(getUserAge(userWithoutAge))

What is the output of this code?

A) User age: 30
Age not provided
B) User age: Some(30)
Age not provided
C) User age: 30
User age: None
D) None of the above

Question 10: Avoiding Nulls with Option in Method Returns

Analyze the Scala code snippet below that uses Option in method returns to avoid nulls:

def findUsername(userId: Int): Option[String] = {
  if (userId == 1) Some("JohnDoe")
  else None
}

val username1 = findUsername(1).getOrElse("Unknown")
println(username1)

val username2 = findUsername(2).getOrElse("Unknown")
println(username2)

What does this code print?

A) JohnDoe
Unknown
B) Some(JohnDoe)
Unknown
C) JohnDoe
None
D) None of the above

Question 11: Pattern Matching with Options to Handle Nulls

Consider the following Scala code snippet that uses pattern matching with options to handle potential null values:

def getDescription(word: Option[String]): String = {
  word match {
    case Some(w) => s"Found word: $w"
    case None => "No word found"
  }
}

val word1 = Some("Scala")
println(getDescription(word1))

val word2: Option[String] = None
println(getDescription(word2))

What does this code print?

A) Found word: Scala
No word found
B) Found word: Some(Scala)
No word found
C) Scala
None
D) None of the above

Question 12: Encapsulating Nullable References with Options

Analyze the Scala code snippet for encapsulating nullable references within Option to prevent NullPointerExceptions:

def getLength(s: Option[String]): Int = {
  s.getOrElse("").length
}

val str1: Option[String] = Some("Hello")
println(getLength(str1))

val str2: Option[String] = None
println(getLength(str2))

What is the output of this code?

A) 5
0
B) Some(5)
None
C) 5
Some(0)
D) None of the above

Question 13: Creating and Accessing a Map

Consider the following Scala code snippet demonstrating how to create and access elements of a Map:

val capitals = Map("France" -> "Paris", "Japan" -> "Tokyo", "India" -> "New Delhi")

println(capitals.get("France"))
println(capitals.getOrElse("Germany", "Not found"))

What is the output of this code?

A) Some(Paris)
Not found
B) Paris
Not found
C) Some(Paris)
Some(Not found)
D) None of the above

Question 14: Updating and Adding Elements to a Map

Analyze the Scala code snippet below that updates and adds elements to an immutable Map:

var numbers = Map(1 -> "one", 2 -> "two")
numbers = numbers + (3 -> "three")
numbers = numbers.updated(2, "TWO")

println(numbers)

What does this code print?

A) Map(1 -> one, 2 -> TWO, 3 -> three)
B) Map(1 -> "one", 2 -> "two", 3 -> "three")
C) Map(1 -> "one", 2 -> "TWO", 3 -> "three")
D) Compilation error

Question 15: Iterating Over a Map

Review the Scala code snippet involving iterating over a Map:

val ages = Map("Alice" -> 30, "Bob" -> 25, "Charlie" -> 28)

for ((name, age) <- ages) {
  println(s"$name is $age years old")
}

What is the output of this program?

A) Alice is 30 years old
Bob is 25 years old
Charlie is 28 years old
B) Alice: 30
Bob: 25
Charlie: 28
C) Compilation error
D) None of the above

Question 16: Using Options for Safe Access

Examine the Scala code snippet involving Option:

val maybeNum: Option[Int] = Some(5)
val result = maybeNum match {
  case Some(n) => n * 2
  case None => 0
}

println(result)

What is the output of this code?

A) 5
B) 10
C) 0
D) None

Question 17: Handling Exceptions with Try and Match

Review the following Scala code snippet for exception handling:

import scala.util.{Try, Success, Failure}

def divide(a: Int, b: Int): Try[Int] = Try(a / b)

val result = divide(10, 0) match {
  case Success(value) => s"Result: $value"
  case Failure(exception) => s"Error: ${exception.getMessage}"
}

println(result)

What is the output of this code?

A) Result: 10
B) Error: / by zero
C) Error: ArithmeticException
D) Compilation error

Question 18: Using flatMap to Flatten and Transform

Consider the following Scala code snippet that demonstrates the use of the flatMap combinator:

val lists = List(List(1, 2, 3), List(4, 5), List(6))
val flattenedAndDoubled = lists.flatMap(numbers => numbers.map(_ * 2))

println(flattenedAndDoubled)

What does this code print?

A) List(2, 4, 6, 8, 10, 12)
B) List(List(2, 4, 6), List(8, 10), List(12))
C) List(1, 2, 3, 4, 5, 6)
D) None of the above

Question 19: Folding a List with foldLeft

Analyze the Scala code snippet for folding a list:

val numbers = List(1, 2, 3, 4, 5)
val sum = numbers.foldLeft(0)((acc, number) => acc + number)

println(sum)

What is the output of this code?

A) 15
B) 10
C) 5
D) None of the above

Question 20: Basic Usage of zip

Consider the following Scala code snippet demonstrating basic usage of the zip function:

val names = List("Alice", "Bob", "Charlie")
val ages = List(25, 30, 28)
val people = names.zip(ages)

println(people)

What is the output of this code?

A) List(("Alice", 25), ("Bob", 30), ("Charlie", 28))
B) List(Alice25, Bob30, Charlie28) C) [("Alice", 25), ("Bob", 30), ("Charlie", 28)] D) None of the above

Question 21: zip with Unequal Collection Sizes

Analyze the Scala code snippet below that uses the zip function with collections of unequal sizes:

val numbers = List(1, 2, 3, 4)
val letters = List('a', 'b', 'c')
val zippedList = numbers.zip(letters)

println(zippedList)

What does this code print?

A) List((1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'))
B) List((1, 'a'), (2, 'b'), (3, 'c'))
C) List((1, 'a'), (2, 'b'), (3, 'c'), (4, null))
D) Compilation error

Question 22: Using zipWithIndex

Review the Scala code snippet involving the zipWithIndex function:

val fruits = List("apple", "banana", "cherry")
val indexedFruits = fruits.zipWithIndex

println(indexedFruits)

What is the output of this program?

A) List(("apple", 0), ("banana", 1), ("cherry", 2)) B) List(("apple", 1), ("banana", 2), ("cherry", 3)) C) [("apple", 0), ("banana", 1), ("cherry", 2)]
D) None of the above

Question 23: Basic Usage of groupBy

Consider the following Scala code snippet demonstrating the basic usage of the groupBy function:

val words = List("apple", "banana", "pear", "apricot", "peach")
val groupedByFirstLetter = words.groupBy(word => word.head)

println(groupedByFirstLetter)

What is the output of this code?

A) Map('a' -> List("apple", "apricot"), 'b' -> List("banana"), 'p' -> List("pear", "peach"))
B) Map(a -> List("apple", "apricot"), b -> List("banana"), p -> List("pear", "peach"))
C) List("apple", "banana", "pear", "apricot", "peach")
D) None of the above

Correct Answer: B) Map(a -> List("apple", "apricot"), b -> List("banana"), p -> List("pear", "peach"))

Question 24: Higher-Order Functions

Analyze this Scala code snippet that demonstrates a higher-order function:

def performOperation(x: Int, operation: Int => Int): Int = {
  operation(x)
}

val result = performOperation(5, y => y * y)
println(result)

What does this code print?

A) 10
B) 25
C) 5
D) None of the above

Question 25: Simple Recursive Function for Summation

Consider the Scala code snippet below for calculating the sum of numbers from 1 to N:

def sumToN(n: Int): Int = {
  if (n <= 0) 0
  else n + sumToN(n - 1)
}

val sum10 = sumToN(10)
println(sum10)
val sum5 = sumToN(5)
println(sum5)

What is the output of this code?

A) 55 and 15
B) 50 and 15
C) 55 and 10
D) 45 and 10