Class Constructors in Kotlin: A Beginner’s Guide
If you have spent even a day coding, you have probably worked with constructors, maybe even without knowing about it. I never knew that the brackets that follow the class name are called a “primary” constructor or that your can have additional ones.
In this post I will tell you all about them, how you can use them and how they work.
Constructors are an essential part of creating objects in Kotlin. They are special functions that are called when an object of a class is created, and are used to initialize the state of the object and perform other tasks such as setting up resources or validating arguments.
In Kotlin, the compiler automatically generates a default constructor for a class without any parameters. However, in certain situations, it may be necessary to define custom constructors with additional functionality. To do this, the “constructor” keyword is used after the class name.
Classes in Kotlin can have a Primary Constructor and one or more Secondary Constructors.
Primary constructor
The primary constructor is defined immediately after the class name and can have parameters, like regular functions. For example, in the following code, the parameter is “name” of type String:
class Person constructor(val name: String) {
// class body
}
If the class does not have any annotations or access modifiers, the constructor keyword can be omitted:
class Person(val name: String) {
// class body
}
You should remember that the primary constructor cannot contain executable code.
Declaring and initializing properties
In Kotlin, there is a simple way to create and initialize properties when using the primary constructor. Instead of declaring a property and then initializing it separately, you can do it all in the constructor using a concise syntax. It looks like this:
class Person(
val fristName: String,
val lastName: String,
var age: Int
)
Default Values
One of the benefits of using the primary constructor is the ability to assign default values to the constructor’s parameters. This can be particularly useful when creating objects where certain properties are optional or have a common value across instances.
class Person(
val firstName: String,
val lastName: String,
var isEmployed: Boolean = true
)
Here the parameter isEmployed
is set to true
by default.
Annotations and visibility modifiers
In case the constructor has annotations or visibility modifiers, the constructor keyword is required, and the modifiers are placed BEFORE it:
class MyClass @Inject constructor(val name: String) {
// class body
}
The constructor is annotated with @Inject
which can be used for dependency injection, and the constructor keyword is required to indicate that this is a constructor.
The constructor
keyword can also be used with visibility modifiers such as public
, private
, protected
like this:
class MyClass private constructor(val name: String) {
// class body
}
In this example, the class MyClass
has visibility modifier private
which means this constructor can be accessed only within the class.
Secondary constructors
The class may also contain one or more additional constructors. It looks like this:
// Primary constructor
class User(
var firstName: String,
var lastName: String,
var isPlatinum: Boolean = false
) {
// First additional constructors
constructor(firstName: String, lastName: String
): this(firstName, lastName, false) {
println("isPlatinum is False by default.")
}
// Second additional constructors
constructor(firstName: String): this(firstName, "Unknown"){
println("I'm in the 3rd constructor.")
}
}
// main function
fun main() {
var user = User("Donn", "Felker", true)
var friend = User("Jane", "Doe")
var cousin = User("Nick")
}
As you can see, the class User
has a primary constructor that takes three parameters firstName
, lastName
and isPlatinum
(notice that the last parameter is set to false
by default) and also two additional constructors. The first one takes two parameters firstName
and lastName
and the second one takes only one parameter firstName
.
Importance of “this” keyword
The this
keyword is used in secondary constructors to refer and call the primary constructor, passing required parameters to it. In cases where a class has multiple additional constructors, the this
keyword is used to call the previous constructor in the chain.
This helps in initializing properties defined in the primary constructor before initializing properties defined in the secondary constructors. By delegating the initialization of properties to the primary constructor, it ensures that the class’s properties are always in a consistent state.
Why use additional constructors?
Additional constructors can be used to create an instance of a class using any number of parameters available to you.
In our example you can create an instance of the class using the primary constructor by passing all of the three parameters, using the first additional constructor by passing two parameters or the last one by passing only one parameter.
Depending on the number of parameters passed, the corresponding constructor will be called and the properties will be initialized.
Main function code Sequence
It is easier to understand how this works if we look at it as a sequence of code execution. Let’s break down what happens when we call the main function in our code example:
- When creating the
user
object, the primary constructor is called with all three parametersfirstName
,lastName
andisPlatinum
. All good the object is created. - When creating the
friend
object, we are passing only two parameters:firstName
andlastName
. Here the first additional constructor is called. It than calls the primary constructor passing those two parameters and prints the massage "isPlatinum is False by default” since the third parameter is set to “False” in the primary constructor. After this the object is created. - When creating the
cousin
object, we are only passing one parameter –firstName
. Here the second additional constructor is called. It than calls the first additional constructor passing “Nick” as thefirstName
and default value “Unknown” aslastName
. Finally, the primary constructor is called who setsisPlatinum
to “False” since it’s the default value. The massage “I'm in the 3rd constructor.” Is printed after which the object is created.
Conclusion
In conclusion, constructors play a vital role in creating objects in Kotlin. They initialize the state of an object, set up resources, and validate arguments. You might not need this information in the begging of your coding journey, but believe me, you will at some point and I hope you could use this post to freshen up your knowledge on the nature of constructors in Kotlin.
If you enjoyed the post
If you enjoyed this post, please, consider following my page, as I will be posting more Software Development content in the future.
I also plan on posting other interesting things, such as Quality YouTube Channels I have found in my years on the internet and also some other more personal things.