Table of Contents
Excellent tool support and interoperability with Java, Objective C and now Swift act as invaluable hacks for Kotlin programmers. Google’s support and availability of Android Studio for Kotlin have further counterbalanced app development across platforms. This excerpt discusses various features required to leverage Swift knowledge to learn Kotlin, highlighting the similarities and differences between both programming languages. Get a load of Swift code examples and simultaneously walk through towards coding Kotlin equivalents providing an opportunity for developers to get hands-on-experience using their iOS knowledge to construct an Android UI.
Along with some of the parallels like easy syntax, interoperability across platforms, the inheritance of object-oriented features, regular upgrades and less coding; there are some differences between the two languages in a context that drove them apart.
Enumerating the basic features of Swift and Kotlin:
Essential Features in Swift
- Enumerations are strong point.
- Data classes are absent.
- No delegated classes or delegated properties.
- Absence of annotations.
Essential Features in Kotlin
- Classes in Kotlin are final by default.
- Struct or passing by value are absent.
- Absence of tuples.
- No typealias.
- Guard statements are absent.
The quickness with which both languages gained adoption has helped increase the number of developers for both platforms. Swift was initially developed to work with Cocoa Touch Framework, can be mixed with Objective C in projects but is meant to replace it. Kotlin was designed to seemingly interoperate with Java and to make object-oriented features more functional.
Understanding the Similar Points in Kotlin and Swift
Let’s share the similarities, and celebrate the differences in Swift and Kotlin in subsequent discussion. Although Swift is a native iOS app development platform, Kotlin can be used for cross-platform app development. With minor adjustments their syntax looks and behaves in same way:
Similarities |
Swift |
Kotlin |
---|---|---|
Declaring Properties – Mutable as well as immutable properties can be declared with ease in both Swift as well as Kotlin. |
var age: Int = 09
var firstName = “Kon” |
var age: Int = 09
var firstName = “Kon” |
Data Structures – Arrays can be mutable, are collection of strings but not a mixture of strings and integers. But these are declared with fixed size. |
var names = Array<String>()
To append values: To declare immutable array: |
val numbers = Array<Int>(5){0}numbers[1] = 2 //numbers is now (0, 2, 0, 0, 0)
Immutable array: Lists in Kotlin are similar to Swift’s array type: var names = ArrayList<String>() //creates a list of strings, initially with no elements Adding Values: Declaring an Immutable List: val days = listOf(“Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”, “Sun”) |
Swift’s Dictionary and Kotlin’s Map are very useful data structures for storing values. | Creating a Swift Dictionary: var namesWithAges : [String: Int] = [:] namesWithAges.reserveCapacity(20) //define capacityAssigning Values: namesWithAges[“John Doe”] = 34Declaring Immutable Dictionary: let namesWithAges = [“John Doe” : 34, “Jane Doe” : 29] |
var namesWithAges = HashMap<String, Int>()
var namesWithAges = HashMap<String, Int>(20) //define capacity Assigning Values: namesWithAges.put(“John Doe”, 34) While creating immutable map: val namesWithAges = mapOf(“John Doe” to 34, “Jane Doe” to 29) |
High Order Functions –
These make the code readable and maintainable as these operate on other functions by either taking functions as argument or returning a function. |
Prototype of Swift Function:
func functionName(parameterName: DataType) -> ReturnType { Swift default argument: |
Prototype of Kotlin Function: (1) fun functionName(parameterName: DataType): ReturnType { //function body } (2) Taking Function as Parameter/argument: fun passMeFunction(abc: () -> Unit) { // I can take function // do something here // execute the function abc() } (3) Can return a function: passMeFunction( { val user = User() user.name = “PQR”println(“FUNCTIONS ARE EASY” } )An example of Kotlin function: fun greetUser(name: String): String { return “Hello ${name}!” }Kotlin default argument: fun greetUser(name: String = “World”): String { return “Hello ${name}!” } |
Lambda in Kotlin vs. Closure in Swift are useful building blocks in coding arena. | Closures in Swift: var square = { (a: Int) -> Int in return a * a } print(square(4))Taking a cue from above example, in which the type of the variable square has already been established as an integer, the closure can be re-written as: square = { //we can even omit the parameter list $0 * $0 } print(square(3)) //9 |
Using a Lambda in Kotlin:
val square = { a:Int -> Calling a lambda by placeholder object name it for the parameter: Currying functions enable Lambda calculus, and permits to reduce the function to less complex ones which may already exist in your SDK and help reduce the code. |
Nullable types and Kotlin vs. Optional types in Swift – Both Kotlin and Swift languages are “Safe” and cannot have Null/Nill values (by accident).In both these languages such types are represented by a question mark “?” placed to the right of the variable type. |
Optional Type in Swift:
var authToken: String? = “a long string” authToken = nil |
Nullable Type in Kotlin:
var authToken: String? = “some long string” authToken = null |
Null Safety –
|
Swift’s “Nil-coalescing operator” (introduced in Swift 3) works in the same way as Elvis operator in Kotlin.
let id: Int? = nil Besides, “if let” expression is also a proper method to handle optionals: let id: Int? = nil |
Null Safety in Kotlin:
var id: Int? = 15 Kotlin also makes use of Elvis operator to make above situation consice: var id: Int? = null val userId = id ?: -1 //userID is -1 Elvis operator does not let Android developers feel the absence of Guard statement in Kotlin. Elvis operator can also be used with safe cast: fun readyForParade (participant : Bandmember) : Boolean { |
“If Let” expression in Swift vs. “Smart Casts” in Kotlin | In Kotlin as the nullable cast gets its correct type or becomes not null, the cast variable can be used directly for rest of scope of program:
val id: Int? = null |
|
Control Flow -“if-else” statements | Swift adopts parentheses, although the basic if-else statement remains same:
if a > b { |
If-else statement in Kotlin is similar to the syntax in most other languages:
if (a > b) { |
“Switch” Statement | Swift makes use of “Switch” as follows: let x = 3 switch x { case 1: print(“x == 1”) case 2: print(“x == 2”) default: print(“x is neither 1 nor 2”) } |
“Switch” = “When” in Kotlin.
val x = 3 |
“For” Loop | For loop in Swift:
let days = [“Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”, “Sun”] Range operator in Swift differs slightly in Swift: for item in 1..<10 { |
Loops in Kotlin:
val days = arrayOf(“Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”, “Sun”) For Loop by making use of “range operator”: for (item in 1..10) { |
Declaring a class – is almost same in Kotlin and Swift | Example of class declaration in Swift:
class ViewController: UIViewController { } |
Example of class declaration in Kotlin:
class MainActivity: AppCompatActivity() { } |
Constructor in Kotlin vs. Initializer in Swift | Example of Initializer in Swift:
public class Car { init(model: String) { |
Example of Constructor in Kotlin:
class Car constructor(_model: String) { init { |
Extensions – help in extending the existing features of a class. | “Int” class with a functions that returns square of an integer can be extended in Swift as:
extension Int { print(5.square()) //prints 25 |
“Int” class with a functions that returns square of an integer can be extended in Kotlin as:
fun Int.square(): Int { println(5.square()) //prints 25 |
Interface in Kotlin vs. Protocol in Swift | Representation of Protocol: protocol Animal { var canFly: Bool {get}func eat()func makeSound() } |
Representation of Interface: interface Animal { var canFly: Booleanfun eat()fun makeSound() } |
Default Implementation | protocol Animal { var canFly: Bool {get} }extension Animal { var canFly: Bool { return false } } |
interface Animal { val canFly: Booleanget() = true } |
Functional Programming Tools | compactMap, map, filter | filterNotNull, map, filter |
Figure Out the Differences: Kotlin vs Swift?
Dissimilarities |
Swift |
Kotlin |
---|---|---|
“Data Class” in Kotlin vs. “Struct” in Swift | Example of Struct declaration in Swift:
struct Person { let personOne = Person(name: “Jon”, dob: “12 August”) |
Example of Data Class declaration in Kotlin:
val personOne = Person(“ALI”, “11 November”) personTwo.name = “Vanessa” |
“Val” in Kotlin vs. “Let” in Swift | Example of “Let” in Swift:
let persons = [Person(name: “Jonathan”, dob: “12 Sept”), |
Example of “Val” in Kotlin:
val persons = mutableListOf(Person(“Jon”, “12 August”), |
Follow the Footprint: Kotlin vs Swift
Both Kotlin and Swift can be used to develop across platforms, share many features, are highly performant, are used for server-side development, treat declaration of properties, data structures, functions in a similar way; they require programmers to declare variables, classes, and control flow (if-else, for-loop) properly.
While constructor, immutable variables, mutable variables, self-object referencing, arrays, dictionaries/maps, type inference, function declaration, function default parameters, If statements, For loops, Default values, Safe casting, Safe call, Force unwrap, lazy initialization are major points of differences. (Few of these are discussed above)
Frameworks that ease Swift coding include ABI stability, SwiftNIO HTTP2 support, Vapor 4, Swift Package Manager & Xcode, Marzipan – Phase 2, Kitura and theswiftdev.com. Use of Android Studio 3.0 as IDE with fully tested Kotlin support enables developers to make extensive use of Kotlin at website backend. Moreover, it also chalks out the heavy use of kotlin at backend of services for the platforms (OS) the developers are trying to target. While JVM is the most common, Android closely follows it. Spring Boot, Kotlin-Native, Scade, Kotlinx.coroutine, Kotlin.test, Ktor, Anko Commons, Kotlinx.html, Exposed, Anko Coroutines, Anko Layouts, Kotlinx.dom, etc are the most prevalent frameworks that ease creating a mobile app in Kotlin. Quell any signs of dissent, by talking to our experts on Kotlin and Swift app development.