0

There is normal extension function

fun <T> List<T>.test() { }

fun String.test(){ }

and i can declare a variable with extension function type

val obj1 = fun String.(){ }

but can not declare a variable with generic extension function type

val obj2 = fun <T> List<T>.() {} //error

P.S. I don't want to use List<Any>, it is different from generic.

Can someone tell me how to solve it? Thanks!!

GHH
  • 1,713
  • 1
  • 8
  • 21
  • I would expect you will need to define your own interface and implement it, rather than being able to use conventional functions/lambdas. – Louis Wasserman Dec 19 '19 at 02:55

2 Answers2

0

Extension functions are kind of a red herring. Values can't have polymorphic types at all, not just in Kotlin, but in Java, Scala, etc. Depending on why you want it, one approach would be a generic function returning an extension function:

fun <T> obj2Generic() = fun List<T>.() {}
val obj2ForInt = obj2Generic<Int>()
val obj2ForString = obj2Generic<String>()
Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
0

You cannot do it, same as you cannot assign regular (non-extension) generic function to a variable or instantiate a generic class without specifying the type parameter. Try to put yourself in the compiler's shoes: what would be the type of such variable? It would be generic as well, so it is only possible in another generic context.

fun <T> List<T>.test(){ }

val v1 = List::test // No
val v2 = List<String>::test // OK

fun <T> other() {
    val v3 = List<T>::test // OK
    val v4 = fun List<T>.() { } // OK
}
Mafor
  • 9,668
  • 2
  • 21
  • 36