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
thana
01/29/2019, 8:25 AM
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
natpryce
01/29/2019, 8:30 AM
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
}
Then you can inline functions only where you define the key, not wherever you look up a value
natpryce
01/29/2019, 8:37 AM
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
thana
01/29/2019, 8:41 AM
i see, thank you
thana
01/29/2019, 8:43 AM
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 😄