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:
Syntax
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
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
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
- Writing
class Box[T]and thennew Box(1)andset("a"), which fails becauseTis fixed toIntafter creation. - Using
Tas if it had methods, such asvalue.length, without a bound likeT <: String. - Using
Anyinstead of a type parameter, losing type safety.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: