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

TheOnlyTails

02/16/2022, 7:32 PM
Hi! How can I use generic type parameters in lambda types? For example:
Copy code
val list = listOf<<T>(x: T) -> Unit>()
v

Vampire

02/16/2022, 7:55 PM
Where would you then actually define what
T
is?
1
j

Joffrey

02/16/2022, 7:59 PM
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

Tim Oltjenbruns

02/16/2022, 7:59 PM
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

Vampire

02/16/2022, 8:03 PM
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

Joffrey

02/16/2022, 8:05 PM
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

Tim Oltjenbruns

02/16/2022, 8:05 PM
You would have to cast it inside the function
and that’s no use
v

Vampire

02/16/2022, 8:08 PM
Exactly
m

Matthias Geisler

02/16/2022, 8:25 PM
I guess you are looking for fun interfaces -> https://kotlinlang.org/docs/fun-interfaces.html
t

Tim Oltjenbruns

02/16/2022, 8:28 PM
Helpful, yes. But it doesn’t solve the problem of when you have to know the concrete type.
m

Matthias Geisler

02/16/2022, 9:00 PM
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

Sam

02/17/2022, 4:12 PM
4 Views