plinyar
plinyar

Reputation: 323

Reference to extension function?

Is it possible to get reference to an extension function like you may do for usual function (see here)?

I would expect the following code to compile, but now ::String.toSomething is unknown:

fun String.toSomething() = length + 1
val some = listOf("lala", "bebebe").map(::String.toSomething)

Upvotes: 14

Views: 4192

Answers (3)

Jarekczek
Jarekczek

Reputation: 7866

OP defined an extension function as a standalone function. If regarding extension functions being parts of another class, then the reference is impossible. At least Intellij tells me so.

class MyClass {
  // This function cannot be referenced.
  fun Application.myExt() {
    return "value"
  }
}

As a workaround I did such thing:

class MyClass {
  fun getMyExtFunction: (Application.() -> Unit) {
    return {
      return "value"
    }
  }
}

Now instead of referencing a function, I return this function from another method. The outcome is the same.

Upvotes: 5

elect
elect

Reputation: 7190

Do you mean like this?

fun String.toSomething() = length + 1
val some = listOf("lala", "bebebe").map(String::toSomething)

Just remember to put :: always before the function

Upvotes: 7

Grzegorz Piwowarek
Grzegorz Piwowarek

Reputation: 13773

Referencing extension methods in Kotlin can be done by applying the :: operator between the class name and method name:

val function = Object::myExtensionMethod

so in your case:

fun String.toSomething() = length + 1
val some = listOf("lala", "bebebe").map(String::toSomething)

Upvotes: 15

Related Questions