Thuta Learning
IntermediateProgrammingbeginner

Constructors

Relax. We'll talk through this in plain words — no textbook voice.

A constructor is the setup pattern that lets you feed initial data into a class when you create an object. In Kotlin, you can write the primary constructor right after the class name, which keeps the code short and clear.

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

fun main() {
    val person = Person("John", 35)
    println("${person.firstName} is ${person.age} years old.")
}
You should see
John is 35 years old.

Summary

A constructor is essential for feeding correct data into an object right when it's created.

Easy traps

  • If you get the constructor parameter order wrong, the data can end up meaning something different. Using named arguments makes it clearer.

Practical example — named arguments

Practical example — named arguments

kotlin
class Course(val title: String, val durationHours: Int)

fun main() {
    val course = Course(
        title = "Kotlin Foundation",
        durationHours = 12
    )

    println("${course.title}: ${course.durationHours} hours")
}

You'll know it worked when: Kotlin Foundation: 12 hours

Constructors | Thuta Learning