Scala Traits and Type System 2 — Questions and Answers
Question 1: What is a type class in Scala?
- A class with type parameters
- A pattern using traits and implicits to add behavior to existing types without inheritance (Correct answer)
- A class annotated with @TypeClass
- An abstract class for types
Correct answer: A pattern using traits and implicits to add behavior to existing types without inheritance
Type classes are a pattern in Scala that uses traits and implicit parameters to define behavior for types outside their hierarchy.
Question 2: What is the `Nothing` type in Scala?
- An alias for null
- The type of exceptions; it is a subtype of every type (Correct answer)
- A unit type
- An empty trait
Correct answer: The type of exceptions; it is a subtype of every type
`Nothing` is at the bottom of the Scala type hierarchy and is a subtype of every type, used for expressions that never return.
Question 3: What does covariance (`+T`) mean for a Scala generic type?
- T can only be a supertype
- If A extends B, then Container[A] extends Container[B] (Correct answer)
- The type is mutable
- T must be compared with Ordering
Correct answer: If A extends B, then Container[A] extends Container[B]
A covariant type parameter `+T` means that if `A` is a subtype of `B`, then `Container[A]` is also a subtype of `Container[B]`.
Question 4: What is an implicit conversion in Scala?
- A cast using asInstanceOf
- An automatic type conversion triggered by the compiler when types don't match (Correct answer)
- An explicit call to a convert method
- A runtime reflection operation
Correct answer: An automatic type conversion triggered by the compiler when types don't match
Implicit conversions are functions marked `implicit` that the compiler calls automatically to convert one type to another when needed.
Question 5: Which Scala construct is used to define an abstract type member?
- type T <: AnyRef inside a trait (Correct answer)
- abstract type T
- type T = _
- opaque type T
Correct answer: type T <: AnyRef inside a trait
Abstract type members are declared inside a trait or abstract class using `type T` with optional upper/lower bounds like `T <: AnyRef`.
Question 6: What does the `final` modifier on a Scala class mean?
- The class has no constructor
- The class cannot be extended (subclassed) (Correct answer)
- All methods are immutable
- The class compiles to a final bytecode
Correct answer: The class cannot be extended (subclassed)
Marking a Scala class `final` prevents any other class from extending it, useful for security and optimization.
What is a type class in Scala?