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

Generics

Generics let a class or function work with many types by using a placeholder, like a box labeled 'for anything' that you specify later. You write the code once and use it with any type.

In this page:

  1. Generics
Syntax
scala
class Box[T](value: T) {
  def get: T = value
}

def function_name[T](param: T): T = param

val box = new Box[Type](value)

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)
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Writing class Box[T] and then new Box(1) and set("a"), which fails because T is fixed to Int after creation.
  2. Using T as if it had methods, such as value.length, without a bound like T <: String.
  3. Using Any instead of a type parameter, losing type safety.
🔒

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.