Scala Scala Basics and Syntax 1 — Questions and Answers
Question 1: Which keyword is used to declare an immutable variable in Scala?
- var
- val (Correct answer)
- let
- const
Correct answer: val
In Scala, `val` declares an immutable (read-only) variable that cannot be reassigned after initialization.
Question 2: What is the output of `println(10 / 3)` in Scala?
- 3.33
- 3 (Correct answer)
- 4
- Error
Correct answer: 3
Integer division in Scala truncates the decimal, so 10 / 3 yields 3.
Question 3: How do you define a function in Scala?
- function foo() {}
- def foo() {} (Correct answer)
- fun foo() {}
- func foo() {}
Correct answer: def foo() {}
In Scala, functions are defined using the `def` keyword followed by the function name and parameter list.
Question 4: Which of the following is a valid Scala string interpolation syntax?
- "Hello $name"
- s"Hello $name" (Correct answer)
- f"Hello $name"
- b"Hello $name"
Correct answer: s"Hello $name"
The `s` prefix enables simple string interpolation in Scala, allowing variables to be embedded directly in strings.
Question 5: What does the `Unit` type represent in Scala?
- A null value
- An empty collection
- The absence of a meaningful return value (Correct answer)
- An error type
Correct answer: The absence of a meaningful return value
`Unit` in Scala is analogous to `void` in Java and indicates that a function does not return a meaningful value.
Question 6: Which symbol is used for the 'not equal' operator in Scala?
- <>
- != (Correct answer)
- ~=
- =/=
Correct answer: !=
Scala uses `!=` as the not-equal operator, consistent with Java and many other languages.
Which keyword is used to declare an immutable variable in Scala?