intermediate18 min

Classes and Primary Constructors

Kotlin's concise primary constructor syntax and class property declarations.

What you'll learn

  • Declare a class with a primary constructor directly in the class header
  • Distinguish val and var properties declared in a primary constructor
  • Add a method to a class and call it on an instance

Explanation

Kotlin classes can declare their primary constructor directly in the class header, dramatically reducing boilerplate compared to languages requiring a separate constructor body just to assign fields: class Person(val name: String, var age: Int) declares a class with two properties, a constructor accepting both, and no additional code needed.

The val/var before each constructor parameter is what makes it a property (accessible as person.name) rather than just a local constructor parameter -- val for a read-only property, var for a mutable one, exactly like the standalone variable rules from earlier in this course.

You create an instance without a new keyword (unlike Java or C#): val ada = Person("Ada", 30). Methods are declared inside the class body: class Person(val name: String, var age: Int) { fun greet() = "Hi, I'm $name" }, called as ada.greet().

Guided lab

Predict: A class with a primary constructor and a method

KotlinNot executed
This lab does not run in your browser or on VisaSparkSchools's servers. Read the code, predict what it does, then reveal the real expected output.

Read this program and predict exactly what it prints.

class Person(val name: String, var age: Int) {
    fun haveBirthday(): String {
        age += 1
        return "$name is now $age"
    }
}

fun main() {
    val ada = Person("Ada", 30)
    println(ada.haveBirthday())
    println(ada.age)
}

Stuck? Get a hint.

Common mistakes

  • Writing `new Person(...)` out of habit from Java/C# -- Kotlin doesn't use a `new` keyword for object creation.
  • Forgetting `val`/`var` before a primary-constructor parameter, which makes it a plain constructor parameter (not accessible afterward) instead of a property.
  • Declaring a property as `val` when the design actually needs to mutate it later, causing a compile error at the point of reassignment.

Knowledge check

Knowledge check

1. What keyword does Kotlin require to create a new class instance?
2. In `class Person(val name: String, var age: Int)`, what does the `val` before `name` do?
3. Where are a Kotlin class's methods declared?

Takeaway

A primary constructor with val/var parameters declares both the constructor and the properties in one line -- no `new` keyword is needed to instantiate.

Summary

Kotlin classes declare a primary constructor directly in the header; val/var parameters become properties; instances are created without `new`.

References

Your notes

Notes save automatically.

Finished this lesson?

Mark it complete to track your progress and schedule a future review.

Next: Data Classes