0
0
KotlinConceptBeginner · 3 min read

What is Primary Constructor in Kotlin: Simple Explanation and Example

In Kotlin, a primary constructor is a concise way to declare and initialize class properties directly in the class header. It simplifies object creation by combining property declaration and constructor parameters in one place.
⚙️

How It Works

Think of a primary constructor as the main entrance to a class where you can quickly set up the important details about an object. Instead of writing extra code inside the class to create and assign values to properties, Kotlin lets you do this right next to the class name.

This is like filling out a form at the door before entering a building, so everything is ready inside. The primary constructor takes parameters, and if you prefix them with val or var, Kotlin automatically creates properties for you and assigns the values.

This makes your code shorter and easier to read, especially when you just want to store some data in an object.

💻

Example

This example shows a class Person with a primary constructor that takes a name and age. The properties are declared and initialized in one line.

kotlin
class Person(val name: String, var age: Int)

fun main() {
    val person = Person("Alice", 30)
    println("Name: ${person.name}, Age: ${person.age}")
}
Output
Name: Alice, Age: 30
🎯

When to Use

Use a primary constructor when your class mainly holds data or simple properties that need to be set when creating an object. It is perfect for data classes, simple models, or any case where you want to avoid writing extra code for property initialization.

For example, when creating user profiles, configuration settings, or small objects that represent real-world things, the primary constructor keeps your code clean and straightforward.

Key Points

  • The primary constructor is declared in the class header after the class name.
  • Parameters prefixed with val or var become properties automatically.
  • It simplifies class definitions by combining declaration and initialization.
  • Secondary constructors or init blocks can be used for extra setup if needed.

Key Takeaways

The primary constructor lets you declare and initialize properties in one place.
Use val or var in the constructor to create properties automatically.
It makes your class code shorter and easier to read.
Ideal for simple data-holding classes and models.
You can add extra initialization with init blocks if needed.