Search code examples
kotlinextension-methods

Differenence between ways to declare functions in Kotlin


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

Solution

  • 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.