Dive into the world of generics and parametric polymorphism in Scala. Understand type parameters, bounds, variance annotations, and higher-kinded types with these 30 carefully crafted MCQs for Scala enthusiasts.
Generics and Parametric Polymorphism in Scala
1. Type Parameters and Bounds
What is a type parameter in Scala?
A) A specific type that is fixed at compile time
B) A placeholder for a type that is determined at runtime
C) A placeholder for a type that is passed as a parameter to a class or method
D) A type used for inheritance only
How do you specify a type parameter in Scala?
A) class ClassName[T]
B) def methodName[T](param: T)
C) class ClassName(type T)
D) def methodName(param: T)
What is the purpose of type bounds in Scala?
A) To specify the types that a parameter must be a subtype of
B) To declare a fixed type for a parameter
C) To enable the use of abstract types
D) To restrict a function’s return type
Which of the following represents a type bound that restricts a type to be a subclass of a specific class?
A) class MyClass[A <: SomeClass]
B) class MyClass[A >: SomeClass]
C) class MyClass[A <: Any]
D) class MyClass[A :> SomeClass]
What does the >: operator represent in Scala’s type bounds?
A) It restricts the type to be a subtype of a given type
B) It restricts the type to be a supertype of a given type
C) It specifies an abstract type
D) It limits the return type of a function
Which of the following is the correct syntax for defining a type parameter with an upper bound in Scala?
A) class MyClass[A <: Number]
B) class MyClass[A >: Number]
C) class MyClass[A :> Number]
D) class MyClass[A =: Number]
What does the lower bound (>:) constraint imply for a type parameter?
A) The type parameter must be a subtype of the specified type
B) The type parameter must be a supertype of the specified type
C) The type parameter must be an exact match of the specified type
D) The type parameter must be a different type than the specified one
What is the purpose of using a + sign before a type parameter in a Scala class or method?
A) It indicates a contravariant type
B) It indicates a covariant type
C) It specifies a lower bound for the type
D) It specifies an upper bound for the type
How would you specify a method with a type parameter that can accept any type that is a subclass of Animal?
A) def method[T <: Animal](param: T)
B) def method[T >: Animal](param: T)
C) def method[T <: Any](param: T)
D) def method[T](param: T)
What does the <: operator represent in Scala’s type bounds?
A) It restricts the type to be a supertype of a given type
B) It restricts the type to be a subtype of a given type