Hi! How can I use generic type parameters in lambd...
# getting-started
t
Hi! How can I use generic type parameters in lambda types? For example:
Copy code
val list = listOf<<T>(x: T) -> Unit>()
v
Where would you then actually define what
T
is?
1
j
Since you're creating an instance of this list there, you would have to define T right at this moment anyway, so what would be the point of using a generic type? If you want to create a list of functions that accept any type of arguments, use
Any
or
Any?
instead of
T
t
Copy code
val list: List<(Int) -> String> = listOf<(Int) -> String>({ x: Int -> ""})
Without generics this is the fully-qualified way to define a list here If you had this inside a class that had a generic, this is an option.
Copy code
class MyClass<T> {
    val list: List<(T) -> String> = listOf<(T) -> String>({ x: T -> ""})
}
If you had a function with generics:
Copy code
fun <T> myFunction(): List<(T) -> String> = listOf<(T) -> String>({ x: T -> ""})

val list: List<(Int) -> String> = myFunction<Int>()
Remove the details and verbosity when you figure it out, but I recommend starting by fully qualifying all the types. That will help give you more precise and helpful compiler errors.
v
That's exactly what I meant with "where would you define `T`". If it is defined by an outer scope it could simply be used. But from the broken example in the OP, he wants to do it without a generic type from outer scope
@Joffrey
If you want to create a list of functions that accept any type of arguments, use 
Any
 or 
Any?
 instead of 
T
This actually also does not work:
Copy code
val list = listOf<(Any) -> Unit>({ s: String -> Unit }, { s: Exception -> Unit })
1
j
I spoke too fast actually. You're right. The variance is the opposite, you can't do anything with a list of a arbitrary functions. What you can do is pass a list of functions that all accept
Any
t
You would have to cast it inside the function
and that’s no use
v
Exactly
m
I guess you are looking for fun interfaces -> https://kotlinlang.org/docs/fun-interfaces.html
t
Helpful, yes. But it doesn’t solve the problem of when you have to know the concrete type.
m
Ah...I misread the question...I bet you look for something like:
Copy code
val list = listOf<Function1<*, Unit>>(
    { x: Int -> x+2 }
)
However the caller of the list needs to know then which index holds which lambda.
s