Learn Kotlin · 14/18

Generics: Writing Reusable, Type-Safe Code

6 min read

Generics: Writing Reusable, Type-Safe Code 🧱

Hey there, budding Kotlin developer! 👋 Ever feel like you're writing the same code over and over again for different data types? Like a function that sorts a list of numbers, and then another one that sorts a list of strings? It can get pretty repetitive, right? This is where the magic of Generics comes in, allowing you to write flexible, reusable, and safe code.

Generics are a way to create classes, interfaces, and functions that can work with any data type. Think of them as templates. You define a blueprint, and then you can create specific versions of that blueprint for different types. This not only saves you from writing redundant code but also helps catch errors at compile-time rather than at runtime, which is a huge win!

Let's dive into how you can become a master of generics in Kotlin.

Generic Classes and Functions: The '<T>' Syntax 📦

The Problem: Imagine you need a box. Sometimes you want to put an apple in it, sometimes a book, and other times your car keys. Without generics, you'd need to create a specific AppleBox, BookBox, and KeyBox. That's a lot of boxes!

The Solution: A generic Box! In Kotlin, we use angle brackets (<>) to declare a type parameter, conventionally named T (for Type).

A generic class looks like this:

kotlin
class Box<T>(val item: T)

fun main() {
    // A box for an Integer
    val numberBox = Box<Int>(10)
    println("The number in the box is: ${numberBox.item}")

    // A box for a String
    val textBox = Box<String>("Hello, Kotlin!")
    println("The text in the box is: ${textBox.item}")
}

In this example, Box<T> is a generic class. When we create an instance like Box<Int>(10), we're specifying that this particular box can only hold integers. The compiler enforces this, so if you try to put a string in numberBox, you'll get a compile-time error. This is what we mean by type-safe.

Generic functions work similarly. Let's say we want a function that prints any type of item.

kotlin
fun <T> printItem(item: T) {
    println("Here's your item: $item")
}

fun main() {
    printItem(42)
    printItem("Generics are cool!")
}

The <T> before the function name declares it as a generic function. The compiler is smart enough to infer the type, so you don't even have to explicitly state it when calling the function.

Under the Hood: At compile time, the Kotlin compiler replaces the generic type T with the actual type you've specified (like Int or String). This process is called type erasure, which means the type information is not available at runtime. But don't worry, we have a trick for that later!

Type Bounds: Constraining Generic Types ⛓️

The Problem: What if you want to create a generic function that only works on numbers? For instance, a function that calculates the sum of a list. You can't add strings or other non-numeric types together.

The Solution: Type bounds to the rescue! You can restrict the types that can be used as type arguments. The most common way to do this is to specify an upper bound.

kotlin
fun <T : Number> sum(list: List<T>): Double {
    var total = 0.0
    for (element in list) {
        total += element.toDouble()
    }
    return total
}

fun main() {
    val numbers = listOf(1, 2.5, 3f)
    println("The sum is: ${sum(numbers)}") // This works!

    // val strings = listOf("a", "b", "c")
    // println(sum(strings)) // This will give a compile-time error!
}

In this example, <T : Number> means that T can be any type that is a subtype of Number (like Int, Double, Float, etc.). If you try to call this function with a list of strings, the compiler will complain because String is not a Number. This is incredibly useful for ensuring that your generic code can only be used with types that have the necessary properties or functions.

Variance Simplified: Understanding 'in' and 'out' ↔️

The Problem: Imagine you have a function that takes a List<Any>. Can you pass a List<String> to it? Intuitively, it seems like you should be able to, since String is a subtype of Any. However, by default, generic types in Kotlin are invariant, meaning a List<String> is not a subtype of List<Any>. This might seem strange, but it's to prevent certain types of runtime errors.

The Solution: Kotlin provides the out and in keywords to control the variance of generic types, making them more flexible.

  • out (Covariance): Think of this as "produce" or "read-only." If a generic type is marked with out, it means you can use a subtype as a substitute. The List interface in Kotlin is a great example. It's declared as List<out T>. This means you can assign a List<String> to a variable of type List<Any>.

    kotlin
    fun printAll(items: List<Any>) {
        items.forEach { println(it) }
    }
    
    fun main() {
        val strings = listOf("a", "b", "c")
        printAll(strings) // This is allowed because List is covariant
    }

    A class with an out type parameter can only use that type in "out" positions, meaning as a return type of a function. It can't be used as a parameter for a function that modifies the object.

  • in (Contravariance): Think of this as "consume" or "write-only." If a generic type is marked with in, you can use a supertype as a substitute. A good example is the Comparable interface, which is declared as Comparable<in T>.

    kotlin
    val stringComparator: Comparator<Any> = Comparator { a, b ->
        a.toString().compareTo(b.toString())
    }
    
    // You can use a Comparator<Any> where a Comparator<String> is expected
    val strings = mutableListOf("c", "a", "b")
    strings.sortWith(stringComparator)
    println(strings)

    A class with an in type parameter can only use that type in "in" positions, meaning as a parameter to a function. It cannot be a return type.

A Fun Fact: The terms "covariance" and "contravariance" might sound intimidating, but they are just fancy words to describe how subtyping relationships are preserved (or reversed) for generic types.

Reified Type Parameters: Preserving Types at Runtime 🔍

The Problem: As mentioned earlier, due to type erasure, the type information of a generic parameter T is not available at runtime. This can be a limitation if you need to know the exact type, for instance, when you want to check if an object is an instance of T.

The Solution: Kotlin offers a special keyword, reified, for inline functions. A reified type parameter allows you to access the type at runtime.

kotlin
inline fun <reified T> isInstanceOf(value: Any): Boolean {
    return value is T
}

fun main() {
    println(isInstanceOf<String>("hello"))    // true
    println(isInstanceOf<Int>("hello"))       // false
}

Here, because isInstanceOf is an inline function and T is reified, we can use value is T to check the type at runtime. This is a powerful feature that's often used in libraries and frameworks for things like serialization and dependency injection.

Industry Practice: While reified is powerful, remember that it only works with inline functions. Inline functions can sometimes increase the size of your compiled code because the function's body is copied to every call site. So, use it judiciously where you genuinely need runtime type information.


Further Reading & Resources 📚

To continue your journey into the world of Kotlin generics, here are some helpful resources:

Challenge

Your task is to implement a generic data processing class in Kotlin that leverages type bounds, variance, and reified types.

  1. Define a generic class named DataProcessor<T>.
  2. The type parameter T must be constrained by an upper bound to only accept types that implement the Comparable<T> interface.
  3. The class must have a private primary constructor that accepts a List<T> and stores it in a private property.
  4. Implement a public method within the class called getMax() which returns the largest element from the stored list. If the list is empty, it should return null.
  5. Create a companion object inside DataProcessor.
  6. Inside the companion object, define a generic factory function from(items: List<out T>): DataProcessor<T> that takes a list of a subtype of T (using covariance) and returns a new instance of DataProcessor<T>.
  7. Finally, implement an inline extension function for the DataProcessor<T> class called filterIsInstance<R>(). This function must use a reified type parameter R to filter the data processor's internal list and return a new List<R> containing only the elements of the specified type R.

Expected result

Your code should consist of three main parts:

  1. A generic class DataProcessor<T : Comparable<T>> with a private constructor and a getMax(): T? method that correctly finds the maximum value in its internal list.

  2. A companion object within DataProcessor containing the factory function fun <T : Comparable<T>> from(items: List<out T>): DataProcessor<T>. This function should properly instantiate the DataProcessor class.

  3. An inline extension function with the signature inline fun <T : Comparable<T>, reified R> DataProcessor<T>.filterIsInstance(): List<R>. The body of this function must correctly iterate through the processor's items and return a list containing only the elements that are an instance of the reified type R.

kotlin

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.