Generics
In this page:
Generics
A generic class or function uses a type parameter, like class Box[T], so the same definition works with any type while staying fully type-safe. The concrete type is supplied (or inferred) when the class is instantiated or the function is called, such as Box[Int] or Box[String]. This avoids duplicating the same logic for every type you need it to support.
Note: Generic type parameters are conventionally named single uppercase letters like T, A, or K/V for key-value pairs.
Example: Generics
class Box[T](private var value: T) {
def get: T = value
def set(newValue: T): Unit = { value = newValue }
}
object Main extends App {
val intBox = new Box[Int](42)
val strBox = new Box[String]("hello")
println(intBox.get)
println(strBox.get)
}
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: