Swift constructs for Kotlin

If you have used Swift for iOS development, chances are that you really miss its flexibility when developing for Android with Java. Kotlin brings all the Swift goodness to Java that combines OO and functional features and is focused on interoperability, safety, clarity and tooling support. Let’s see a few Swift constructs and their equivalent on Kotlin:

Unwrapping

In Swift, we unwrap with guard let

guard let unwrapped = wrapped else {
  return
}

In Kotlin, we use the elvis operator

val unwrapped = wrapped ?: return

Blocks and Lambdas

In Swift, we can reference parameters without specifying the complete signature using $0, $1, …

let doubleNumbers = numbers.map { $0 * 2 }

In Kotlin, we use it

val doubleNumbers = numbers.map { it * 2 }

Named Parameters

Swift uses named parameters

addNumber(1, with: 2) // Call with named parameters

func addNumber(number: Int, with: Int) {
  return number + with
}

Kotlin has named parameters too

addNumber(1, with = 2) // Call with named parameters

fun addNumber(number: Int, with: Int): Int = number + with

Computed Properties

We define computed properties with (optional) getter in Swift

var name: String {
  return "\(firstName) \(lastName)"
}

Computed properties defined with get in Kotlin

val name: String
  get() {
    return "$firstName $lastName"
  }

Or even smaller with = syntax

val name: String
  get() = "$firstName $lastName"

String templates

We write string templates like "\(firstName) \(lastName)" in Swift and "$firstName $lastName" in Kotlin

Published 13 May 2016

I build mobile and web applications. Full Stack, Rails, React, Typescript, Kotlin, Swift
Pulkit Goyal on Twitter