Does Kotlin has extension class to interface like Swift

In Swift, we could extend a class with an interface as below

extension MyExtend {
   public var type: String { return "" }
}

extension MyOrigin: MyExtend {
   public var type: ListItemDataType {
       return "Origin"
   }
}

Do we have that capability in Kotlin? (e.g. extend an interface)

1 answer

  • answered 2018-05-16 05:13 l'L'l

    Yes, Kotlin does have Extensions — similar to Swift.

    Swift:

    class C {
        func foo(i: String) { print("class") }
    }
    
    extension C {
        func foo(i: Int) { print("extension") }
    }
    
    C().foo(i: "A")
    C().foo(i: 1)
    

    Kotlin:

    class C {
        fun foo(i: String) { println("class") }
    }
    
    fun C.foo(i: Int) { println("extension") }
    
    C().foo("A")
    C().foo(1)
    

    Output:

    class
    extension
    

    There are some key differences you'll want to read up on.

    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.

    We would like to emphasize that extension functions are dispatched statically, i.e. they are not virtual by receiver type. This means that the extension function being called is determined by the type of the expression on which the function is invoked, not by the type of the result of evaluating that expression at runtime.

    https://kotlinlang.org/docs/reference/extensions.html