https://kotlinlang.org logo
Title
c

cookiecookiecookie

02/03/2020, 12:29 AM
so can you do like
var m3 = mutableMapOf<String, Any
d

deactivateduser

02/03/2020, 12:37 AM
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

cookiecookiecookie

02/03/2020, 12:38 AM
i agree it’s not ideal but this is just for prototyping something
thanks i’ll try that out
yep worked thanks!
👍 1
s

satyan

02/03/2020, 7:47 AM
If you have a finite number of value’s types you could use a sealed class.
sealed class MyValue {
   data class FirstType(val value: Int): MyValue()
   data class SecondType(val value: Float): MyValue()
}
m

Matteo Mirk

02/03/2020, 9:18 AM
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

cookiecookiecookie

02/04/2020, 12:37 AM
thank you!
👍 1