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!!

1
  • I would expect you will need to define your own interface and implement it, rather than being able to use conventional functions/lambdas. Commented Dec 19, 2019 at 2:55

2 Answers 2

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
}
Sign up to request clarification or add additional context in comments.

Comments

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>()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.