Home > Back-end >  Differenence between ways to declare functions in Kotlin
Differenence between ways to declare functions in Kotlin

Time:12-03

I have seen some code declaring functions as seen below. What is the difference between fun1 and fun2?

interface Test {
    fun fun1() : Boolean = false
}

fun Test.fun2() : Boolean = true

CodePudding user response:

fun1 defined inside the interface describes an open function that any implementer of the interface can override. Since it also defines a default implementation by returning something, it is not abstract and implementing classes can choose not to override it.

fun2 is an extension function. When these are used with interfaces, often the reason is to discourage overriding. An extension function cannot be overridden, but it can be hidden by another extension function with the same signature, but only in a specific scope. Therefore, some implementer of Test in another module that passes its instance back to this module cannot change the functionality of fun2 as used in this module.

CodePudding user response:

The second version is an extension function.

The difference is that extension functions can be applied to any type (even outside of your code), but they do not have access to private members of that type. They are pretty much the same as calling function with this type as a first parameter, just nicer syntax

  • Related