Kotlin Primary Constructor 🎯

beginner
6 min

Kotlin Primary Constructor 🎯

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.

What is a Constructor in Kotlin? 📝

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.

What is a Primary Constructor in Kotlin? 💡

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.

Creating a Class with a Primary Constructor ✅

Let's create a simple class named Person with a primary constructor that takes name and age as arguments.

kotlin
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 Primary Constructor 📝

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.

kotlin
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.

Primary Constructor with Default Values 💡

You can provide default values for constructor parameters to make the class more flexible and easier to use.

kotlin
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.

kotlin
val person1 = Person() // Name: John Doe, Age: 30

Secondary Constructor 📝

A secondary constructor is used when you want to provide multiple ways to create objects of the same class with different parameters.

kotlin
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.

kotlin
val person2 = Person("Alice") // Name: Alice, Age: 0

Quiz Time! 🎯

Quick Quiz
Question 1 of 1

What 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! 🚀