Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. Kotlin Dictionary
  3. class / Constructor

class / Constructor

Classes in Kotlin are defined with the class keyword. You can write the primary constructor directly in the class header, and place initialization logic in an init block. Secondary constructors use the constructor keyword.

Syntax

// Primary constructor (most common form)
class Person(val name: String, var age: Int)

// Use an init block for initialization logic.
class User(val name: String, val age: Int) {
    init {
        require(age >= 0) { "Age must be 0 or greater" }
    }
}

// Secondary constructor (constructor keyword)
class Point {
    val x: Double
    val y: Double
    constructor(x: Double, y: Double) {
        this.x = x
        this.y = y
    }
    constructor(value: Double) : this(value, value)  // delegation
}

Syntax reference

SyntaxDescription
class ClassName(val x: Type)A primary constructor that declares properties directly.
init { }An initialization block that runs when an instance is created.
constructor(params) { }Defines a secondary constructor.
: this(args)Delegates to another constructor.
private constructorMakes the constructor private (e.g., for the factory pattern).

Sample code

// Primary constructor with property declarations
class Person(
    val name: String,
    var age: Int,
    val email: String = ""  // default argument
) {
    // The init block runs after the constructor.
    init {
        require(name.isNotBlank()) { "Name cannot be blank" }
        require(age >= 0) { "Age must be 0 or greater" }
        println("Person instance created: $name (age $age)")
    }

    // Computed property
    val greeting: String
        get() = "Hello, I'm ${name}!"
}

// Example of a secondary constructor
class Rectangle(val width: Double, val height: Double) {
    val area: Double = width * height

    // Secondary constructor for squares
    constructor(side: Double) : this(side, side)
}

// Private constructor (factory pattern)
class Database private constructor(val url: String) {
    companion object {
        fun create(url: String): Database {
            println("Connecting to database: $url")
            return Database(url)
        }
    }
}

fun main() {
    // Create an instance using the primary constructor
    val alice = Person("Alice", 30, "alice@example.com")
    println(alice.greeting)

    // Use the default argument.
    val bob = Person("Bob", 25)
    println("Bob's email: '${bob.email}'")  // empty string

    // Call the constructor with named arguments.
    val carol = Person(name = "Carol", age = 28)
    println("Carol's age: ${carol.age}")

    // Secondary constructor
    val rect = Rectangle(4.0, 3.0)
    val square = Rectangle(5.0)  // square
    println("Rectangle area: ${rect.area}")  // 12.0
    println("Square area: ${square.area}")  // 25.0

    // Factory pattern
    val db = Database.create("jdbc:mysql://localhost/mydb")
    println("Connected to: ${db.url}")

    // Validation in init (invalid arguments throw an exception)
    try {
        Person("", 25)
    } catch (e: IllegalArgumentException) {
        println("Error: ${e.message}")
    }
}

Notes

Kotlin classes are far more concise than their Java equivalents when it comes to constructors. Because you can declare properties directly in the primary constructor, the field declaration, constructor body, and assignment that Java requires are all condensed into a single line.

You can write multiple init blocks; they are executed in order from top to bottom. A secondary constructor must always delegate to the primary constructor using : this(...).

For classes focused purely on holding data, see data class. For inheritance and overriding, see open / override.

If you find any errors or copyright issues, please .