“Unused” Type Parameters on Kotlin Inline Classes

Kotlin introduced inline classes in 1.3 as an experimental feature. They allow wrapping of a single value which is inlined at compile time. You can use them for ID classes and also for logging implementations. They are a great feature with some very interesting use cases.

“Unused” type parameters can actually be very useful on inline classes. Take the following as an example.

The above defines a Key inline class which has an associated type parameter and inlines to a String. The Kotlin compiler claims this type paramter is unused but it can actually be used in function signatures.

The above Context class is type safe at compile time but all the type parameter information is erased at runtime. Create Keys for all the information you want to store in Context and getting and setting will be type safe. Feel free to play around with the following example.

I’m interested to see others’ ideas on how this can be used so please share them in the comments! Enjoy!

Written by

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store