Scala Traits and Type System 1 — Questions and Answers
Question 1: What is a Scala trait?
- A final class with static methods
- An abstract type similar to a Java interface that can contain concrete implementations (Correct answer)
- A type alias
- A wrapper around a Java class
Correct answer: An abstract type similar to a Java interface that can contain concrete implementations
A Scala trait is like a Java interface but can contain concrete method and field implementations, enabling mixin composition.
Question 2: How do you mix a trait into a class in Scala?
- class Foo implements Bar
- class Foo inherits Bar
- class Foo extends Bar
- class Foo with Bar (Correct answer)
Correct answer: class Foo with Bar
Use the `with` keyword to mix additional traits into a class after the initial `extends` declaration.
Question 3: What is the diamond problem in OOP and how does Scala solve it?
- A pattern for diamonds; solved by generics
- Ambiguity from multiple inheritance; Scala uses linearization to determine method resolution order (Correct answer)
- A null pointer issue; solved with Option
- A compilation error; solved with sealed traits
Correct answer: Ambiguity from multiple inheritance; Scala uses linearization to determine method resolution order
Scala resolves the diamond problem through C3 linearization, establishing a deterministic method resolution order for mixed-in traits.
Question 4: What is a type alias in Scala?
- A renamed import
- A new name given to an existing type using `type` (Correct answer)
- An implicit conversion
- A supertype declaration
Correct answer: A new name given to an existing type using `type`
The `type` keyword creates an alias for an existing type, improving code readability without creating a new type.
Question 5: What is variance in Scala generics?
- The variability of runtime performance
- How subtyping relationships of type parameters relate to subtyping of parameterized types (Correct answer)
- The mutability of generic collections
- The version of the generic API
Correct answer: How subtyping relationships of type parameters relate to subtyping of parameterized types
Variance annotations (`+A` for covariance, `-A` for contravariance) control how generic type relationships map to subtype relationships.
Question 6: What does `implicit` mean when applied to a parameter in Scala?
- The parameter is optional
- The compiler automatically finds and passes a matching value from implicit scope (Correct answer)
- The parameter is lazily evaluated
- The parameter is inherited from a trait
Correct answer: The compiler automatically finds and passes a matching value from implicit scope
Implicit parameters are automatically supplied by the compiler by searching for matching implicit values in scope, enabling type-class patterns.
What is a Scala trait?