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)
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With