Is somethink like type safe heterogenous container...
# announcements
t
Is somethink like type safe heterogenous containers even possible with kotlin? http://www.informit.com/articles/article.aspx?p=2861454&seqNum=8
n
Yes. Even better, you can use reified generics and the
as?
operator so that the type is inferred by the compiler and the caller does not have to pass in a class instance.
t
do you have an example? i cannot imagine how it would look like. also i thought
reified
only works for ionline functions. how can i build a map this way?
n
Something like...
Copy code
class Example {
     fun store = mutableMapOf<String, Any>()

     operator fun set(key: String, value: Any) {
          store[key] = value
     }

    inline operator fun <reified T:Any> get(key:String): T? =
        store[key] as? T
}
To avoid confusing errors I like to define a type for keys that know the type of the value, rather than index by bare strings. Here’s an example that’s similar to your case: https://github.com/npryce/konfig/blob/master/src/main/kotlin/com/natpryce/konfig/konfig.kt#L85
Then you can inline functions only where you define the key, not wherever you look up a value
But that does come at the cost of a bit more boilerplate code to define all the typed keys that the program will use
t
i see, thank you
i already have some boilerplate to circumvent this problem (which is even harder for me, because the value of the map re in fact SAMs and the key should represent the type of this key). I think im better of then with my existing boilerplate 😄