Type parameterization in Scala is a feature that allows you to define classes, traits, and methods that can work with different types. Type parameters are placeholders for types that are specified when a class or method is instantiated. Here’s an overview of type parameterization in Scala:
1. Defining type parameters: To define a type parameter in Scala, use the square brackets notation ([]) and a type parameter name. Here’s an example:
“
class Box[T](value: T) {
def getValue: T = value
}
val intBox = new Box[Int](42)
val strBox = new Box[String](“hello”)
`
In this example, “Box” is a class that takes a type parameter “T”. The constructor for “Box” takes a single value of type “T”, and the “getValue” method returns that value. We create two instances of “Box”, one with type parameter “Int” and one with type parameter “String”.
2. Using type parameters: Once you have defined a class or method with a type parameter, you can use that type parameter to specify types within the class or method. Here’s an example:
“
class Pair[T, U](first: T, second: U) {
def swap: Pair[U, T] = new Pair(second, first)
}
val pair = new Pair(1, “hello”)
val swappedPair= pair.swap
println(swappedPair) // prints Pair(hello,1)
`
In this example, “Pair” is a class that takes two type parameters “T” and “U”. The constructor for “Pair” takes two values, one of type “T” and one of type “U”, and the “swap” method returns a new instance of “Pair” with the types swapped.
3. Bounds on type parameters: You can also specify bounds on type parameters to restrict the types that can be used with a class or method. Here’s an example:
“
class Box[T <: Number](value: T) {
def getValue: T = value
}
val intBox = new Box[Int](42)
val doubleBox = new Box[Double](3.14)
// val strBox = new Box[String]("hello") // does not compile
`
In this example, “Box” is a class that takes a type parameter “T” with an upper bound of “Number”. This means that “T” must be a subtype of “Number”. We create two instances of “Box”, one with type parameter “Int” and one with type parameter “Double”, which are both subtypes of “Number”. We try to create a third instance with type parameter “String”, which is not a subtype of “Number” and does not compile.
Overall, type parameterizationin Scala is a powerful feature that allows you to define classes, traits, and methods that can work with different types. Type parameters are placeholders for types that are specified when a class or method is instantiated, and you can use them to specify types within the class or method. You can also specify bounds on type parameters to restrict the types that can be used with a class or method. By using type parameterization, you can write more generic and reusable code that can work with different types, which is a fundamental aspect of Scala’s functional programming paradigm.