Reified type parameters in Kotlin

Level 5418 keystrokes

Generic type arguments are normally erased at runtime, but in an inline function a reified T keeps its real type, so it can be used in type checks and T::class. Here it filters a mixed list by type and gets a class name.

Kotlin code

// reified requires inline; the call site's real type replaces T
1inline fun <reified T> List<*>.filterIsInstanceTo(): List<T> {
// Keeps only elements of type T (this also needs a reified type)
2 return this.filterIsInstance<T>()
3}
4
// Without reified, T::class would not compile
5inline fun <reified T> typeName(): String {
// simpleName is the class name without the package, or null for anonymous classes
6 return T::class.simpleName ?: "Unknown"
7}
8
// A List<Any> mixing Int, String and Double
9val mixed = listOf(1, "hello", 2.5, "world", 3)
// T = String: ["hello", "world"]
10val strings = mixed.filterIsInstanceTo<String>()
// T = Int: [1, 3] (2.5 is a Double, so it is excluded)
11val ints = mixed.filterIsInstanceTo<Int>()
12
// Print Strings: [hello, world]
13println("Strings: $strings")
// Print Ints: [1, 3]
14println("Ints: $ints")
// Print Type: Double
15println("Type: ${typeName<Double>()}")

Output

Strings: [hello, world]
Ints: [1, 3]
Type: Double
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.

  • "× 12
  • (× 10
  • )× 10
  • :× 8
  • <× 8
  • >× 8
  • .× 6
  • ,× 4
  • {× 3
  • }× 3

More Kotlin examples at level 5

← Kotlin typing practice