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 T1class Box<T>(val value: T) { // Returns the stored value with its original type T2 fun get(): T = value // Prints the value inside a string template3 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: 428intBox.display()// Print Value: Hello9strBox.display()Output
Value: 42 Value: Hello
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