Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Kotlin has extension class to interface like Swift

Tags:

swift

kotlin

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)

like image 330
Elye Avatar asked May 16 '18 04:05

Elye


People also ask

What is extension class in Kotlin?

Kotlin extensions provide the ability to extend a class with new functionality without implementing the inheritance concept by a class or using design pattern such as Decorator. These extensions basically add some functionality in an existing class without extending the class.

How do I extend a class in Kotlin?

We cannot extend a data class but in order to implement the same feature, we can declare a super class and override the properties in a sub-class.

Is Kotlin extension of Java?

Kotlin code can be easily called from Java. For example, instances of a Kotlin class can be seamlessly created and operated in Java methods. However, there are certain differences between Java and Kotlin that require attention when integrating Kotlin code into Java.


1 Answers

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

like image 97
l'L'l Avatar answered Sep 20 '22 13:09

l'L'l