Welcome to our tutorial on Kotlin Primary Constructor! In this comprehensive guide, we'll dive deep into understanding the primary constructor in Kotlin, a modern and intuitive programming language for Android and other JVM platforms.
Before we delve into the primary constructor, let's briefly understand what a constructor is. In object-oriented programming, a constructor is a special method that is used to create objects. It initializes the properties or fields of an object.
A primary constructor in Kotlin is the constructor that is defined by default when you create a class. It's responsible for initializing the instance variables of the class.
Let's create a simple class named Person with a primary constructor that takes name and age as arguments.
class Person(val name: String, val age: Int)In the above code, val denotes that the name and age are read-only properties.
Initializer blocks in Kotlin are used to initialize properties or perform other setup tasks before the primary constructor is called. They are enclosed within curly braces {} and are placed right after the constructor parameters.
class Person(val name: String, val age: Int) {
init {
println("Initializing Person: $name, $age")
}
}In this example, an initializer block is used to print a message when a Person object is created.
You can provide default values for constructor parameters to make the class more flexible and easier to use.
class Person(val name: String = "John Doe", val age: Int = 30)Now, if you create a Person object without providing arguments, it will use the default values.
val person1 = Person() // Name: John Doe, Age: 30A secondary constructor is used when you want to provide multiple ways to create objects of the same class with different parameters.
class Person(val name: String, val age: Int) {
constructor(name: String) : this(name, 0)
}In this example, we've created a secondary constructor that initializes a Person with only a name. The age is set to the default value, 0.
val person2 = Person("Alice") // Name: Alice, Age: 0What is the default name and age of a `Person` object created without providing arguments?
With this, we've covered the basics of the primary constructor in Kotlin. As you progress, you'll encounter more advanced concepts and techniques. Happy coding! 🚀