What if you could create objects with all their data ready, without writing extra setup code every time?
Why Primary constructor and init blocks in Kotlin? - Purpose & Use Cases
Imagine you want to create a class to represent a person. You write code to set the name and age manually inside the class body, repeating the same steps every time you create a new person.
This manual way is slow and easy to mess up. You might forget to set a value or write extra code that makes your class messy and hard to read.
Primary constructors and init blocks let you set up your class neatly and quickly. You can pass values right when you create an object, and the init block helps run extra setup code automatically.
class Person { var name: String = "" var age: Int = 0 fun setup(name: String, age: Int) { this.name = name this.age = age } }
class Person(val name: String, val age: Int) { init { println("Person created: $name, $age years old") } }
You can create clear, concise classes that automatically handle setup, making your code easier to write and understand.
When building an app, you can quickly create user profiles by passing their info directly to the class, and the init block can check if the data is valid right away.
Primary constructors let you pass data when creating objects.
Init blocks run extra setup code automatically after the constructor.
This approach keeps your classes clean and your code simple.