CodeBlanks Logo Icon CodeBlanks

Constructor

Learn to define the class constructor.

Constructor: initialising with a primary constructor

In Kotlin the primary constructor is written next to the class name. If you mark a parameter with val or var it becomes both a property and a constructor parameter.

class Person(val name: String)

val p = Person("Alex")
println(p.name)  // Alex

The constructor forces a value to be set when an instance is created. val name declares both the parameter and an immutable property in one line. This is the core of Kotlin's concise class syntax.

Calling the constructor

To call the constructor you write the values in parentheses after the class name. You access properties with a dot.

val p = Person("Alex")
println(p.name)

Person("Alex") creates a new instance and sets name. You then read it via p.name. If you used var the value could change later; val stays fixed.

Practice Add a name property to Person

Define class Person(val name: String). In main create val p = Person("Alex") and print p.name with println.

Starter code

Main.kt
fun main() {
    // Define a Person class with a name property
    // Create an instance and print its name
}

Sample solution

Main.kt
class Person(val name: String)

fun main() {
    val p = Person("Alex")
    println(p.name)
}

Expected output

Ayşe

Questions and answers

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

1 Fill in the blank: declare with val

Question
class Person(____ name: String)
Answer
class Person(val name: String)

Explanation: val name becomes both a property and a constructor parameter.

2 What does class Person(val name: String) do?

  • Only declares a constructor
  • Only declares a property
  • Defines the name property and a constructor Correct answer
  • Declares a method

Explanation: val name is both a property and a constructor parameter.

3 Match piece to role

Term Meaning
class Person Class
val name Property
Person("Alex") Instance
p.name Access

All lessons in Beginner