Scala Scala Basics and Syntax 2 — Questions and Answers
Question 1: What is the correct way to define a Scala object (singleton)?
- class MyObject
- singleton MyObject
- object MyObject (Correct answer)
- static class MyObject
Correct answer: object MyObject
The `object` keyword in Scala creates a singleton object, ensuring only one instance exists.
Question 2: Which collection is immutable by default in Scala?
- scala.collection.mutable.List
- java.util.ArrayList
- scala.collection.immutable.List (Correct answer)
- scala.collection.mutable.Map
Correct answer: scala.collection.immutable.List
Scala's default `List` from `scala.collection.immutable` is immutable and cannot be modified after creation.
Question 3: What does `_` represent when used as a wildcard in Scala imports?
- Import nothing
- Import all members (Correct answer)
- Import only public members
- Import static members
Correct answer: Import all members
In Scala, `import package._` imports all public members from a package, similar to Java's `import package.*`.
Question 4: How are Scala classes instantiated?
- MyClass.create()
- new MyClass() (Correct answer)
- MyClass.instance()
- MyClass()
Correct answer: new MyClass()
Scala classes are instantiated using the `new` keyword followed by the class name and constructor arguments.
Question 5: What is the Scala equivalent of Java's `System.out.println`?
- Console.log
- println (Correct answer)
- System.println
Correct answer: println
Scala provides a top-level `println` function that writes a line to standard output, wrapping Java's `System.out.println`.
Question 6: Which Scala construct is used to represent optional values and avoid null?
- Either
- Try
- Option (Correct answer)
- Result
Correct answer: Option
`Option[A]` in Scala represents a value that may or may not be present, with subtypes `Some(value)` and `None`.
What is the correct way to define a Scala object (singleton)?