``` data class Foo(val one: String, val two: Strin...
# announcements
d
Copy code
data class Foo(val one: String, val two: String) {
    fun bar() = println(one + two)
}

fun Foo.bar() = println(one + two)
Can anybody explain me the difference? Is it just another way of writing the same functionality? Are there rules when it is better to use member functions and when extension functions? I thought of extension functions of mostly useful to extend third party code.
d
In this case it does behave the same, but keep in mind that extension functions are always resolved statically. There is no way to
override
an extension function or make it abstract. They are just syntactic sugar for top-level functions where the first parameter is denoted as a receiver.
r
The first one will be compiled as a method of
Foo.class
, the second one as a static method of
TheFileKt.class
taking a
Foo
as parameter
h
Both provide the same functionality, but the implementation is slightly different: Extension methods are (in Java terms) static methods, that get the receiver as the first object.
I also use extension methods mostly for third party code.
d
Thanks guys! That pretty much sums it up for me!
d
public member functions suppose to represent core interface of the class, everything that is not core, supposed to be an extension, like all utils functions etc
m
if I remember well, the scope of the two functions is different. to use the extension function you have to import it (as you would do with static methods btw)