← Back to Scala Course | Chapter 12: Advanced Features | Lesson 3 of 7

Generics

In this page:

  1. Generics

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

markup
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)
}
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.