Hello, I have a question regarding generics. I wo...
# getting-started
m
Hello, I have a question regarding generics. I would like to store lambdas into a Map. And those lambdas have a generic parameter. So, I did this simple code
Copy code
typealias AFunction<R, A> = suspend (args: A) -> Result<R>

val functionMap = mutableMapOf<String, AFunction<Any?, Any?>>()

fun <R, A> addFunctionToMap(name: String, function: AFunction<R, A>) {
    functionMap[name] = function
}
For some reasons, it doesn’t compile (on the line
functionMap[name] = function
) as it is saying it was expecting a type
AFunction<Any?, Any?>
and not
AFunction<R, A>
. I tried modifying a bit the
addFunctionToMap
function like this:
Copy code
fun <R: Any?, A: Any?> addFunctionToMap(name: String, function: AFunction<R, A>) {
    functionMap[name] = function
}
But, it doesn’t change the compiler error. Do you have an idea how I could solve that? 🙏
t
Try to use „out Any?“ on definition side inside of just „Any?“
r
MutableMap<String, AFunction<*, *>>
m
MutableMap<String, AFunction<*, *>>
works .. but Then if I try to call the function in it, the compiler tells me the parameter is of type
Nothing
(because of the Star projection).
r
Of course not. Storing random generic functions in a map isn't type safe. You either need to cast it, or store type information with the functions somehow.
(or both)
m
What you need to solve the lack of type-safety here is the Typesafe Heterogeneous Container pattern: https://stevewedig.com/2014/08/28/type-safe-heterogenous-containers-in-java/