BeginnerOOP

Primary Constructor

Pass data into a class via its constructor.

kotlin
class Student(val name: String, val age: Int)

fun main() {
    val student = Student("Rahul", 21)
    println(student.name)
    println(student.age)
}
Output
Rahul 21

Explanation

The primary constructor defines properties directly in the class header using val or var.

Related Tutorials