Type-safe heterogeous map in Kotlin

Note: if “advertising” a library is considered spamming, please remove this topic.

I implemented a type-safe heterogeous map pattern as described in Effective Java by Joshua Bloch. If you are not familiar with this data structure, it is a map that could store values of different types and still provides a strongly typed API to access its contents. One example of a similar data structure is CoroutineContext, for example coroutineContext[Job] returns a Job object while coroutineContext[CoroutineName] returns String.

As this is a utility of a very generic usage, it is not related to any specific technology, etc., but to programming in Kotlin in general, I decided to post it here to ask for your opinions and suggestions.

Project can be found here: https://github.com/brutall/typedmap . I tried to design the API to be as smooth as possible, by utilizing Kotlin’s goodness such as: advanced type inferring, reified types, etc.

It supports accessing items by type:

map += User("alice")

val user = map.get<User>()

It supports defining typed keys, similarly as in CoroutineContext:

object Username : TypedKey<String>()

map[Username] = "alice"
val username = map[Username]

It supports storing multiple values per a key type, similarly to regular maps:

data class UserKey(val id: Int) : TypedKey<User>()

map[UserKey(1)] = User(1, "alice")
map[UserKey(2)] = User(2, "bob")

val alice = map[UserKey(1)]
val bob = map[UserKey(2)]

It is actually a pretty simple util. Please let me know what do you think!

1 Like