Learning Kotlin and Swift
Kotlin vs Swift: The Init Construction
Explore Kotlin and Swift together and learn their differences
In Mobile development, the 2 major programming language to learn is Swift and Kotlin. They look very similar, but there are subtle differences.
Let’s look at the one called during construction, the init
that exist in both Kotlin and Swift.
The init function
In Swift, init
is the constructor and is called before the parent is constructed.
In Kotlin, the init
is not really a constructor, and it is called after the parent is constructored.
More details below.
In Swift
- The
init
function can have parameters to form a constructor for the class. - Cannot have more than one
init()
function in the class (i.e. empty parameter constructor) - The
init
function is called before the parent constructor is called i.e. the parent object is not yet formed. - The
init
function cannot call the class member function unless it’s a static function. The reason is because the parent is not constructed yet, so the child object is not constructed yet.
class Base {
private let someString: String
init(someString: String) {
print("In Base init")
self.someString = someString
}
}class Child: Base {
init() {
print("In Child init")
super.init(someString: ChildClass.localStaticFunction())
}static func localStaticFunction() -> String {
print("In local static function")
return "something"
}
}
The result of the above code will be
In Child class init
In local static function
In Base init
In Kotlin
- The
init
scope cannot have parameters to form a constructor for the class. Theconstructor
is the actual constructor function that can have parameter. - Can have more than one
init
scope in the class. The execution order dependent of the order where it is placed - The
init
scope is called after the parent constructor is called i.e. the parent object is already formed. (note, theconstructor
function is also called after the parent is constructed) - The
init
scope can call the class member function .The reason is because the object has been constructed.
open class Base {
private val something: String
constructor(something: String) {
this.something = something
println("In Base constructor")
}
init {
println("In Parent Init")
}Base}class Child: Base {
constructor(something: String): super(something) {
println("In Child Constructor")
}
init {
println("In Child Init")
localFunction()
}
private fun localFunction() {
println("In Local Function")
}
}
The result of the above code will be
In Base Init
In Base constructor
In Child Init
In Local Function
In Child Constructor
Summary
To summarize, I have put them side by. side for easier comparison.

If you like the above, you might also be interested in