How to use default parameters in Kotlin constructor:
We might need to initialize a class by passing a parameter to the constructor or without using that parameter. In Java, this problem is handled by creating multiple constructors or by overloading the constructor.
Kotlin provides an easy and concise way to do it. We can have parameters called default parameters to handle it.
It means that we can provide default values to the parameter. If we pass any value to these parameters, that will be used, else it will use the default value.
We don’t have to create different constructors to handle that.
Example to use default parameters in constructor:
Let’s consider the below example program :
class User(private val name: String = "", private val age: Int = 0) {
fun getMessage(): String {
return if (age > 10) {
"Hi ${name}, Welcome to our App !"
} else {
"Hi ${name}, You can't use this App :)"
}
}
}
fun main(args: Array<String>) {
val user1 = User()
val user2 = User("Alex")
val user3 = User("Bob", 9)
val user4 = User("Chandler", 12)
println(user1.getMessage())
println(user2.getMessage())
println(user3.getMessage())
println(user4.getMessage())
}
Here, we have one class called User with two default parameters for the constructor : name and age. By default, name is an empty string and age is equal to 0.
In the main method, we are creating three variables of User. user1 is created without passing any parameter to the constructor. user2 is created by passing only the name to the constructor, user3 is created by passing name and age to the constructor and user4 is created in a same way as user3.
If you run this program, it will print the below output:
Hi , You can't use this App :)
Hi Alex, You can't use this App :)
Hi Bob, You can't use this App :)
Hi Chandler, Welcome to our App !
As you can see, it takes the default values if we don’t pass anything to the constructor and executes the program.