Scala Scala Basics and Syntax 3 — Questions and Answers
Question 1: What is the result of `List(1, 2, 3).head` in Scala?
- 3
- 2
- 1 (Correct answer)
- None
Correct answer: 1
The `head` method on a Scala List returns the first element, which is 1 in this case.
Question 2: Which Scala keyword is used to extend a class?
- implements
- inherits
- extends (Correct answer)
- super
Correct answer: extends
Scala uses the `extends` keyword for class inheritance, allowing a subclass to inherit fields and methods from a parent class.
Question 3: What is the difference between `==` and `eq` in Scala?
- There is no difference
- == checks reference equality; eq checks value equality
- == checks value equality; eq checks reference equality (Correct answer)
- eq is not a valid operator
Correct answer: == checks value equality; eq checks reference equality
In Scala, `==` performs structural (value) equality while `eq` checks reference identity (same object in memory).
Question 4: How do you create an Array of integers in Scala?
- Array.of(1,2,3)
- int[] arr = {1,2,3}
- Array(1, 2, 3) (Correct answer)
- new Array[Int](1,2,3)
Correct answer: Array(1, 2, 3)
Scala provides the companion object syntax `Array(1, 2, 3)` to create an array using the `apply` factory method.
Question 5: What does `lazy val` do in Scala?
- Creates a mutable variable
- Evaluates a value immediately at declaration
- Defers evaluation of a value until first access (Correct answer)
- Creates a thread-safe singleton
Correct answer: Defers evaluation of a value until first access
`lazy val` in Scala defers the computation of a value until the first time it is accessed, then caches the result.
Question 6: Which method converts a Scala List to an Array?
- toArray (Correct answer)
- asArray
- convertToArray
- arrayOf
Correct answer: toArray
Calling `.toArray` on any Scala collection converts it to an `Array`, making the elements available in array form.
What is the result of `List(1, 2, 3).head` in Scala?