Kotlin extension functions vs member functions
Asked Answered
J

4

18

I am aware that extension functions are used in Kotlin to extend the functionality of a class (for example, one from a library or API).

However, is there any advantage, in terms of code readability/structure, by using extension functions:

class Foo { ... }

fun Foo.bar() {
    // Some stuff
}

As opposed to member functions:

class Foo {

    ...

    fun bar() {
        // Some stuff
    }
}

Is there a recommended practice?

Jordison answered 8/11, 2017 at 13:55 Comment(2)
See also: When should one prefer Kotlin extension functions?Ferment
Here you can see how an extension function is compiled youtube.com/watch?v=wAQCs8-a6mgAcidulous
H
17

From my point of view, there are two compelling reasons to use extension functions:

  1. To "extend" the behaviour of a class you're not the author of / can't change (and where inheritance doesn't make sense or isn't possible).

  2. To provide a scope for particular functionality. For example, an extension function may be declared as a freestanding function, in which case it's usable everywhere. Or you may choose to declare it as a (private) member function of another class, in which case it's only usable from inside that class.

It sounds like #1 isn't a concern in your case, so it's really more down to #2.

Howl answered 8/11, 2017 at 14:1 Comment(4)
Yes, I am the original author of the class (it's for a personal project) so #1 isn't a concern. Could you explain exactly what you mean by providing scope for a particular functionality? Thanks.Jordison
@FarbodSalamat-Zadeh - I've added a little detail to #2 - let me know if that helps clarify.Howl
Thanks, that's great!Jordison
You can find detail explanation here about #2.Roer
F
23

When to use member functions

You should use member functions if all of the following apply:

  • The code is written originally in Kotlin
  • You can modify the code
  • The method makes sense to be able to use from any other code

When to use extension functions

You should use extension functions if any of the following apply:

  • The code was originally written in Java and you want to add methods written in Kotlin
  • You cannot change the original code
  • You want a special function that only makes sense for a particular part of the code

Why?

Generally, member functions are easier to find than extension functions, as they are guaranteed to be in the class they are a member of (or a super class/interface).

They also do not need to be imported into all of the code that uses them.

Fishman answered 8/11, 2017 at 14:1 Comment(0)
H
17

From my point of view, there are two compelling reasons to use extension functions:

  1. To "extend" the behaviour of a class you're not the author of / can't change (and where inheritance doesn't make sense or isn't possible).

  2. To provide a scope for particular functionality. For example, an extension function may be declared as a freestanding function, in which case it's usable everywhere. Or you may choose to declare it as a (private) member function of another class, in which case it's only usable from inside that class.

It sounds like #1 isn't a concern in your case, so it's really more down to #2.

Howl answered 8/11, 2017 at 14:1 Comment(4)
Yes, I am the original author of the class (it's for a personal project) so #1 isn't a concern. Could you explain exactly what you mean by providing scope for a particular functionality? Thanks.Jordison
@FarbodSalamat-Zadeh - I've added a little detail to #2 - let me know if that helps clarify.Howl
Thanks, that's great!Jordison
You can find detail explanation here about #2.Roer
R
4

Extension functions are similar to those you create as a utility functions.

A basic example would be something like this:

// Strings.kt
fun String.isEmail() : Boolean {
    // check for email pattern and return true/false
}

This code can be written as a utility function in Java like this:

class StringUtils {
    public static boolean isEmail(String email) {
        // check for email pattern and return true/false
    }
}

So what it essentially does is, calling the same function with the object you call on will be passed as the first parameter to the argument. Like the same function I have given example of in Java.

If you want to call the extension function created in kotlin from java, you need to pass the caller as the first argument. Like,

StringsKt.isEmail("[email protected]")

As per the documentation,

Extensions do not actually modify classes they extend. By defining an extension, you do not insert new members into a class, but merely make new functions callable with the dot-notation on variables of this type.

They are simply static functions with the caller as the first argument and other parameters followed by it. It just extends the ability for us to write it that way.

When to create extension functions?

  • When you don't have access to that class. When that class belongs to some library you have not created.
  • For primitive types. Int, Float, String, etc.

The another reason for using extension function is, you don't have to extend that class in order to use the methods, as if they belong to that class (but not actually part of that class).

Hope it makes a bit clear for you..

Rozanna answered 11/11, 2017 at 6:55 Comment(0)
D
0

As mentioned in other answers, extension functions are primarily used in code that you can't change - maybe you want to change complex expression around some library object into easier and more readable expression.

My take would be to use extension functions for data classes. My reasoning is purely philosophical, data classes should be used only as data carriers, they shouldn't carry state and by themselves shouldn't do anything. That's why I think you should use extension function in case you need to write a function around data class.

Dialectical answered 16/6, 2021 at 11:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.