Generics
scala> List(1,2,3,4)
val res0: List[Int] = List(1, 2, 3, 4)
scala> val optX = Option(3)
val optX: Option[Int] = Some(3)
case class Pair[A](first: A, second: A)
// defined case class Pair
scala> val intPair = Pair[Int](3, 4)
val intPair: Pair[Int] = Pair(3,4)
scala> val doublePair = Pair[Double](1.1, 3.14)
val doublePair: Pair[Double] = Pair(1.1,3.14)
Defining Generic Classes and Traits
In Scala, you can define generic classes and traits using square brackets to specify type parameters.
class Box[T] {
private var content: Option[T] = None
def put(item: T): Unit = {
content = Some(item)
}
def get(): Option[T] = content
}
trait Comparable[T] {
def compareTo(other: T): Int
}
Using Generic Classes
val intBox = new Box[Int]
intBox.put(123)
val stringBox = new Box[String]
stringBox.put("Hello Generics")
println(intBox.get()) // Outputs: Some(123)
println(stringBox.get()) // Outputs: Some("Hello Generics")
Defining and Using Generic Methods
Scala allows defining methods with their own type parameters, which can be useful for utility methods.
object Utils {
def getFirstElement[T](list: List[T]): Option[T] = list.headOption
}
val numbers = List(1, 2, 3)
val names = List("Alice", "Bob", "Charlie")
println(Utils.getFirstElement(numbers)) // Outputs: Some(1)
println(Utils.getFirstElement(names)) // Outputs: Some("Alice")