Kotlin Reified Generics: Explained

Kotlin is a wonderful language full of many little goodies and surprises that make day-to-day development so much more pleasant. Most of its goodies are really just a very smart compiler that does for you much of what you would have done anyway, and reified generics are a great example of that.

Kotlin is a wonderful language full of many little goodies and surprises that make day-to-day development so much more pleasant. Most of its goodies are really just a very smart compiler that does for you much of what you would have done anyway, and reified generics are a great example of that.

If you're sitting there thinking "what the are reified generics, and when should I use them?", then this post is for you. The following is an answer I posted in the Kotlin Slack to that exact question, and figured it might help people out here as well.

In normal Java generics, the generic parameter is only known at compile time, and is erased from the runtime. Kotlin’s reified generics allow you to pretend that the generic is still there at runtime, by effectively swapping out the placeholder <T> with the known type when it is actually used.

For example:

class JavaClass {
    <T> List<T> getList() { ... }
}
// somewhere else
List<String> list = new JavaClass().getList<String>();

effectively compiles in Java to

class JavaClass {
    List getList() { ... }
}
// somewhere else
List list = new JavaClass().getList();

The assumption here is that if the type-checker is able to verify at compile-time that everywhere that T is used, it is safe, then at runtime all calls to that method are safe and that T is not really needed any longer. But there are times that it would be nice to know that T parameter at runtime, which is what reified generics allows for.

An example where you might want to have that T at runtime is getting a value from a map, where the map can hold any type, and your class needs to check the type of the object in the map.

class JavaClass {
    <T> T getItemFromMap(String key) { 
        Object item = _map.get(key); // this is OK
        if(item instanceof T) { // compilation error, T is not known here at runtime
            return (T) item
        }
        else {
            return null;
        }
    }
}

The solution is to pass a Class object matching the T parameter, which has methods to do that check for you:

class JavaClass {
    <T> T getItemFromMap(Class<T> itemClass, String key) { 
        Object item = _map.get(key); // this is OK
        if(itemClass.isAssignableFrom(item.getClass())) { // this works
            return (T) item
        }
        else {
            return null;
        }
    }
}

But now our method is ugly, and we have to pass 2 parameters to it to get it to work, when at compile-time all the information is readily available. Reified generics make it possible to get around this restriction. The JVM fundamentally does not have the ability to make this work at runtime, so reified generics use a trick at compile-time to make it seem like that: it just inlines the function call and replaces the generic parameter with the actual Class in that inlined code.

Going back to the map example, we can rewrite it using reified generics like this:

inline fun <reified T> getItemFromMap(String key) { 
    val item = _map.get(key)
    if(T::class.java.isAssignableFrom(item.getClass())) {
        return (T) item
    }
    else {
        return null;
    }
}
// somewhere else
val list: String = getItemFromMap("key")

effectively compiles to

val item = _map.get(key)
val list: String = if(String::class.java.isAssignableFrom(item.getClass())) {
    (String) item
}
else {
    null;
}

I hope this was helpful!


by: Casey Brooks



Kotlin Coroutines on Android - How to use Coroutines on Android

Kotlin Coroutines on Android - How to use Coroutines on Android

Coroutines are a Kotlin feature that convert async callbacks for long-running tasks, such as database or network access, into sequential code. This Kotlin Coroutines tutorial will show you how to use coroutines on Android, and how the new androidx-concurrent library makes it easy to use them to get things off the main thread. You'll also learn how the new library helps coroutines work with Architecture Components. This session also covers coroutine patterns, best practices, and even how to test coroutines!

Kotlin Coroutines on Android - How to use Coroutines on Android.

Coroutines are a feature of Kotlin that help convert callback-based code into sequential code, making code easier to read, write, and understand. This session will show you how to use coroutines on Android, and how the new androidx-concurrent library makes it easy to use them to get things off the main thread. You'll also learn how the new library helps coroutines work with Architecture Components. This session also covers coroutine patterns, best practices, and even how to test coroutines!

How to use Kotlin - from the Lead Kotlin Language Designer

How to use Kotlin - from the Lead Kotlin Language Designer

In this Kotlin tutorial, the lead Kotlin language designer will show you how you can write more idiomatic Kotlin, what the benefits are, and help you discover some of the most powerful yet lesser known features of Kotlin. Kotlin is similar to the Java programming language, so it's natural that your Kotlin code looks very much like Java code when you are first start to use the language.

Kotlin is similar to the Java programming language, so it's natural that your Kotlin code looks very much like Java code when you are first start to use the language. While this is fine to begin with, you're probably not taking full advantage of all the language benefits. In this session, the lead Kotlin language designer will show you how you can write more idiomatic Kotlin, what the benefits are, and help you discover some of the most powerful yet lesser known features of Kotlin.

Kotlin Programming Fundamentals Tutorial - Learn Kotlin for Beginners

Kotlin Programming Fundamentals Tutorial - Learn Kotlin for Beginners

Kotlin Programming Fundamentals Tutorial - Learn Kotlin for Beginners: Learn programming fundamentals using the Kotlin programming language. Kotlin is an excellent language for GUI Architectures, Libraries, and Server Side Applications. This course will start you off the right way, no matter which path you take with the language. The course features hands-on coding exercises to teach you both Functional, Event Driven, and Object Oriented design patterns.

Kotlin Programming Fundamentals Tutorial - Learn Kotlin for Beginners

Learn programming fundamentals using the Kotlin programming language. Kotlin is an excellent language for GUI Architectures, Libraries, and Server Side Applications. This course will start you off the right way, no matter which path you take with the language. The course features hands-on coding exercises to teach you both Functional, Event Driven, and Object Oriented design patterns.

💻 Code: https://github.com/BracketCove/KotlinCourseSamples

⭐️ Course Contents ⭐️
Section 1
⌨️ (0:00:00) Course Overview: About Me, You, and this Course
⌨️ (0:09:23) How to Run the Examples
⌨️ (0:10:59) Kotlin Syntax Practice for Beginners

Section 2
⌨️ (0:39:26) Data Landscape: Memory Spaces and Named Addresses (References)
⌨️ (0:44:21) How to use "val" and "const val" References to promote Immutability/Efficiency:
⌨️ (0:51:55) Using "var" Reference Types, and the problems with Shared Mutable State!
⌨️ (0:58:58) Giving Structure to Data with Classes

Section 3
⌨️ (1:19:45) A Fundamental Divide: Computation and Control Logic
⌨️ (1:22:52) Computing Data means Solving Problems
⌨️ (1:32:11) Controlling the Flow of Data
⌨️ (1:37:24) Event Driven Programs
⌨️ (1:57:33) Functional versus Imperative Program Style (mild introduction)

Section 4
⌨️ (2:18:38) What is Software Architecture?
⌨️ (2:21:14) Separation of Concerns
⌨️ (2:34:13) Dependency Inversion: Using Interfaces Effectively for Front End and Back End
⌨️ (3:06:22) Extension versus Abstraction: Open/Closed Principle
⌨️ (3:17:00) Dependency Injection: How, What, and Why?
⌨️ (3:30:23) Inversion of Control via the Service Locator Pattern

Section 5
⌨️ (3:44:25) Proving Programs with Tests (a light introduction to Testing)
⌨️ (4:01:42) Solving Problem (Domains) by Analysis