Generic class in Kotlin

Level 4174 keystrokes

Box<T> is a class with a type parameter, so one definition can hold a value of any type. The type argument is inferred from the constructor argument: Box<Int> for 42 and Box<String> for "Hello".

Kotlin code

// T is a type parameter; value has type T
1class Box<T>(val value: T) {
// Returns the stored value with its original type T
2 fun get(): T = value
// Prints the value inside a string template
3 fun display() = println("Value: $value")
4}
5
// T is inferred as Int, giving a Box<Int>
6val intBox = Box(42)
// T is inferred as String, giving a Box<String>
7val strBox = Box("Hello")
// Print Value: 42
8intBox.display()
// Print Value: Hello
9strBox.display()

Output

Value: 42
Value: Hello
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Kotlin code and how often they appear.

  • (× 8
  • )× 8
  • "× 4
  • =× 4
  • :× 3
  • .× 2
  • {× 1
  • }× 1
  • <× 1
  • >× 1

More Kotlin examples at level 4

← Kotlin typing practice