https://kotlinlang.org logo
#getting-started
Title
# getting-started
m

Melvin Biamont

02/21/2021, 6:06 PM
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

Timo Gruen

02/21/2021, 6:25 PM
Try to use „out Any?“ on definition side inside of just „Any?“
r

Ruckus

02/21/2021, 7:06 PM
MutableMap<String, AFunction<*, *>>
m

Melvin Biamont

02/21/2021, 7:27 PM
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

Ruckus

02/21/2021, 7:42 PM
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

Matteo Mirk

02/22/2021, 2:22 PM
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/