CodeBlanks Logo Icon CodeBlanks

Primary constructor

Learn the primary constructor and init block.

Primary constructor

In Kotlin the primary constructor is declared in the class header, inside parentheses. By marking parameters with val or var you turn them directly into properties.

Example: class User(val name: String). Here name is both a constructor parameter and a class property. The body starts with an init block where initialization runs. This gives a short and readable definition.

The init block

The init block runs when an instance is created. Think of it as the body of the primary constructor. Multiple init blocks are allowed; they run top to bottom.

Example: class User(val name: String) { init { println("Ready: $name") } }. Properties are already assigned, so they can be used safely inside init. Parameter validation and side effects go here.

Practice Define the User class

Define a class named User. Its primary constructor takes a val name: String parameter. Add an init block that writes println("Created: $name"). In main create a User instance and print its name property.

Starter code

Main.kt
// Define the User class
// primary constructor: val name: String
// print inside init
// instantiate and print in main

Sample solution

Main.kt
class User(val name: String) {
    init {
        println("Created: $name")
    }
}

fun main() {
    val u = User("Alex")
    println(u.name)
}

Expected output

Created: Alex
Alex

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which is a valid primary constructor definition?

  • function User(name: String)
  • class User(val name: String) Correct answer
  • User class { name: String }
  • def User(name):

Explanation: The class name, a parameter list in parentheses with val gives the primary constructor.

2 Open the class body

Question
class User(val name: String) ____
    init { println(name) }
}
Answer
class User(val name: String) {
    init { println(name) }
}

Explanation: The curly brace opens the class body.

3 Match the parts of a primary constructor

Term Meaning
class User Class header
(val name: String) Parameter list
init { ... } Initialization block
val name Property parameter

All lessons in Intermediate