Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference to extension function?

Tags:

kotlin

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)
like image 500
plinyar Avatar asked Nov 14 '16 15:11

plinyar


People also ask

What is the extension of function?

Extension functions are a cool Kotlin feature that help you develop Android apps. They provide the ability to add new functionality to classes without having to inherit from them or to use design patterns like Decorator.

What is the benefit of extension functions?

Advantages of using Extension Function In general, extension functions have the potential to make your code more brief, readable, and logical by improving and removing boilerplate code from your project. Besides, less code means fewer opportunities for making errors.

What are the extension functions in Kotlin?

Kotlin extension function provides a facility to "add" methods to class without inheriting a class or using any type of design pattern. The created extension functions are used as a regular function inside that class. The extension function is declared with a prefix receiver type with method name.

Where do I put Kotlin extension function?

Yes, extention functions can be declared anywhere you want. For functions of general utilities (regarding lists), I whould place them under something like /company/app/util/lists. kt .


2 Answers

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.

like image 158
Jarekczek Avatar answered Oct 29 '22 08:10

Jarekczek


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)
like image 33
Grzegorz Piwowarek Avatar answered Oct 29 '22 08:10

Grzegorz Piwowarek