so can you do like `var m3 = mutableMapOf<Strin...
# getting-started
c
so can you do like
var m3 = mutableMapOf<String, Any
d
It is technically possible to do something like that, although I don’t really see it as a good programming practice as you will need to handle so many possible cases. The code below will compile. fun main() { var m3 = mutableMapOf<String, Any>() m3["key1"] = "1" m3["key2"] = 2 m3["key3"] = 3.25 m3.forEach{(key, value) -> println ("$key -> $value") } }
c
i agree it’s not ideal but this is just for prototyping something
thanks i’ll try that out
yep worked thanks!
👍 1
s
If you have a finite number of value’s types you could use a sealed class.
Copy code
sealed class MyValue {
   data class FirstType(val value: Int): MyValue()
   data class SecondType(val value: Float): MyValue()
}
m
To use a Typesafe Heterogeneous Map in Java/Kotlin I suggest to use Guava’s implementation: https://www.javadoc.io/doc/com.google.guava/guava/28.2-jre/com/google/common/reflect/TypeToInstanceMap.html If you want to learn how it works, read here: https://stevewedig.com/2014/08/28/type-safe-heterogenous-containers-in-java/ (the author explains the use case coming from Python, just your case 😉 )
c
thank you!
👍 1