Beginner 8 min readKotlin 2.0

Kotlin Classes โ€” Creating and Using Classes

A class is a blueprint for objects. Kotlin classes are concise โ€” properties and constructors can be declared in one line.

What You Will Learn

  • Declare a class with a primary constructor
  • Define properties and methods
  • Create instances
  • Use init blocks
  • Understand val vs var in a class

Basic Class Declaration

Use the class keyword. Properties in the primary constructor are declared with val (read-only) or var (mutable).

Basic Class

kotlin
class Person(val name: String, var age: Int) {
    fun introduce() {
        println("Hi, I am $name and I am $age years old.")
    }
}

fun main() {
    val person = Person("Juned", 25)
    person.introduce()
    person.age = 26  // mutable property
    println(person.age)
}
Output
Hi, I am Juned and I am 25 years old. 26

Person has two properties in the primary constructor. val name cannot be changed. var age can be reassigned. Methods are declared inside the class body.

Beginner Tip: Unlike Java, there is no need for explicit getters and setters โ€” Kotlin generates them automatically for val and var properties.

init Block

The init block runs when an instance is created, after the constructor.

init Block

kotlin
class Circle(val radius: Double) {
    val area: Double

    init {
        require(radius > 0) { "Radius must be positive" }
        area = Math.PI * radius * radius
    }

    fun describe() = "Circle(r=$radius, area=${"%.2f".format(area)})"
}

fun main() {
    val c = Circle(5.0)
    println(c.describe())
}
Output
Circle(r=5.0, area=78.54)

init runs when Circle is created. area is computed inside init. require validates the input and throws if false.

Secondary Constructor

Use constructor keyword for additional constructors.

Secondary Constructor

kotlin
class Book(val title: String, val author: String) {
    var pages: Int = 0

    constructor(title: String, author: String, pages: Int) : this(title, author) {
        this.pages = pages
    }

    override fun toString() = ""$title" by $author ($pages pages)"
}

fun main() {
    val b1 = Book("Kotlin Guide", "KG Team")
    val b2 = Book("Effective Kotlin", "M. Moskala", 350)
    println(b1)
    println(b2)
}
Output
"Kotlin Guide" by KG Team (0 pages) "Effective Kotlin" by M. Moskala (350 pages)

The secondary constructor delegates to the primary with : this(). It sets the pages property afterward.

Best Practice: Prefer default arguments over secondary constructors โ€” they are more concise and readable.

Practice Exercise

Exercisepredict output

What prints? class Dog(val name: String) { fun bark() = println("$name says: Woof!") } fun main() { val d = Dog("Rex") d.bark() }

Quick Quiz

Quick Quiz

In Kotlin, how do you declare a class property in the primary constructor?

Frequently Asked Questions

Related Tutorials

Last updated: 2026-05-01Kotlin 2.0

Written by KotlinGuide Editorial Team ยท Reviewed by KotlinGuide Technical Review