Kotlin Multiplatform / Extensions in Kotlin and Swift: Similarities and Differences

Extensions in Kotlin and Swift: Similarities and Differences

Our virtual library has a detailed article on extensions in Kotlin and Swift. There we tell how one differs from the other with examples and details, and share methods for solving problems in both cases.

This post is a short version of it.

Extensions in Kotlin and Swift differ in syntax. But the essence of extensions for any language is the same: extending the functionality of the class. Here are the examples of the possibilities available to one and the other languages through extensions and which are in demand in practice. Kotlin does not modify the class, but adds a static function. Swift modifies the class directly. In Kotlin, you can create an extension for an optional type, at the same time in Swift ... it would seem impossible, however in fact you can do that (read more in the article)! In Kotlin, the creation of extensions for the generic type is available, while in Swift, this requires a crutch via NSObject. Kotlin allows you to create an extension for a class inside another class, with access to the fields of both classes. In Swift, you cannot create an extension inside a class. Kotlin doesn't have access to the private fields of the class, while Swift does. In Kotlin, you cannot set a new constructor through extensions, while in Swift you can. If you need to implement an interface through an extension, then this is also not for Kotlin, but for Swift. Another extension feature where Swift wins is overriding the parent class's extension function. Kotlin won't help you here.

But they also have something in common: in both Kotlin and Swift, you can add a property as an extension.

We hope you found this post helpful. For more details and code examples, go to the full version of the article at the link.