Introduction to Kotlin for Swift developers - protocols, extensions & generics
Learn how protocols, extensions and generics in Kotlin work from a Swift developer's point of view.
02 Dec 2023 · 8 min read
In the first part of Kotlin for Swift developers, we looked at the basics of Kotlin like variables, functions & control flow.
In the second part, we looked at classes, structs and enums and how those are similar or differentiate from Swift.
In this part, we'll do the same for protocols, extensions and generics.
Let's get started.

Protocols
As an equivalent to Swift protocols, Kotlin provides interfaces. Like Swift's protocols, interfaces in Kotlin can contain declarations of abstract methods and properties as well as method implementations, but cannot store state.
Here is an example of an interface in Kotlin:
interface Purchasable {var price: BigDecimalfun purchase()fun newUserDiscount(): BigDecimal {return price - ...}}class Chocolate : Purchasable {var price: BigDecimal = BigDecimal("3.99")override fun purchase() {// ...}}
As we can see above, we can provide a default method implementation when working with Kotlin interfaces. In Swift, we can achieve the same with protocol extensions.
Extensions
Similar to Swift, Kotlin provides extensions that allow us to extend a class or an interface with new functionality. An example of an extension function in Kotlin might look as follows:
fun Animal.run() {println("Running")}
The equivalent in Swift looks as follows:
extension Animal {func run() {print("Running")}}
Similar to Swift, extensions in Kotlin cannot have stored properties, but computer properties are allowed:
val Animal.description: Stringget() = "name: $name, age: $age"
Generics
Generics are a powerful feature in programming languages that enable us developers to write flexible and reusable code.
Similar to Swift, Kotlin provides the possibility to create generic functions and generic types, for example:
class Stack<Element>(initialItems: Array<Element>) {private var items: Array<Element> = initialItems}val stack = Stack<Int>(intArrayOf(1, 2, 3))
In Swift, the same example looks as follows:
class Stack<Element> {private var items: [Element] = []init(items: [Element]) {self.items = items}}let stack = Stack<Int>(items: [1, 2, 3])
As we can see above, there are almost no differences when defining generic types.
The same applies to generic functions - which look as follows in Kotlin:
fun <Element> add(item: Element) {}fun <Element: SomeInterface> add(item: Element) {}
In Swift:
func add<Element>(item: Element) {}func add<Element: SomeProtocol>(item: Element) {}
As we can see, the only difference is the position of the placeholder type name.



Newsletter
Like to support my work?
Say hi
Related tags
Articles with related topics
Latest articles and tips



