You are currently viewing Type-safe heterogeneous map in Kotlin

Type-safe heterogeneous map in Kotlin

Hi, if anyone is interested, I implemented a type-safe heterogeneous 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.

Project can be found here: 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:

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)]

Please let me know what you think!

submitted by /u/broot__
[link] [comments]