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)
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.
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.
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.
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 .
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With