Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Constructors in Kotlin

What is a Constructor?

In Kotlin, a constructor is a special function that is called when an object is created. It is used to initialize the properties of the object. There are two types of constructors in Kotlin: the primary constructor and secondary constructors.

Primary Constructor

The primary constructor is part of the class header and is defined after the class name. It can take parameters and can be used to initialize properties directly.

Example of Primary Constructor

class Person(val name: String, var age: Int) { fun displayInfo() { println("Name: $name, Age: $age") } }

In the example above, the Person class has a primary constructor that takes two parameters: name and age.

To create an instance of the Person class, you can do the following:

val person = Person("John Doe", 30) person.displayInfo()
Output: Name: John Doe, Age: 30

Secondary Constructor

Secondary constructors allow you to create additional constructors in a class. They are defined using the constructor keyword and can be used to provide multiple ways to instantiate a class.

Example of Secondary Constructor

class Person(val name: String) { var age: Int = 0 constructor(name: String, age: Int) : this(name) { this.age = age } fun displayInfo() { println("Name: $name, Age: $age") } }

In this example, the Person class has a primary constructor that takes only the name, and a secondary constructor that takes both name and age.

You can create an instance using either constructor:

val person1 = Person("Alice") person1.displayInfo()
val person2 = Person("Bob", 25) person2.displayInfo()
Output:
Name: Alice, Age: 0
Name: Bob, Age: 25

Initializer Blocks

In addition to primary and secondary constructors, Kotlin also allows the use of initializer blocks. These blocks are executed when an instance of the class is created, and they can be used to perform additional initialization.

Example of Initializer Block

class Person(val name: String) { var age: Int = 0 init { println("Initialized: $name") } constructor(name: String, age: Int) : this(name) { this.age = age } }

The init block is executed every time an instance of Person is created.

Creating an instance will also trigger the initializer block:

val person = Person("Charlie", 22)
Output: Initialized: Charlie

Conclusion

Constructors in Kotlin are a powerful feature that allows for flexible object creation and initialization. Understanding both primary and secondary constructors, as well as initializer blocks, is essential for effective Kotlin programming. With this knowledge, you can create classes that are easy to initialize and use, making your code more organized and maintainable.