Kotlin Error – Primary Constructor call expected

Kotlin Compilation Error: Primary Constructor call expected occurs when the call to kotlin primary constructor is missing in the definition of kotlin secondary constructor.

This compilation error could be resolved by including a call to the primary constructor, or previous secondary constructors that make a call to the primary constructor, using “this” keyword.

Let us see an example below which recreates Kotlin Primary Constructor call expected – Compile Error

example.kt

</>
Copy
/**
 * Demo program for handling Kotlin Compilation Error Primary Constructor call expected
 */

fun main(args: Array) {    
    val myObj = Student("Arjun", 15)
    myObj.printMsg()
}

class Student(var name: String="") {
    var age: Int = 14
    constructor (name: String, age: Int){
        this.age = age
    }
    fun printMsg(){
        println("Name is $name. Age is $age.");
    }
}

Output

example.kt
Error:(12, 4) Primary constructor call expected
Warning:(12, 17) Parameter 'name' is never used

How to handle Kotlin Primary Constructor call expected – Compile Error

Let us include the call to primary constructor or previous secondary constructors that make a call to the primary constructor. The corrected program is

example.kt

</>
Copy
fun main(args: Array) {    
    val myObj = Student("Arjun", 15)
    myObj.printMsg()
}

class Student(var name: String="") {
    var age: Int = 14
    constructor (name: String, age: Int): this(name){
        this.age = age
    }
    fun printMsg(){
        println("Name is $name. Age is $age.");
    }
}

Output

Name is Arjun. Age is 15.

Conclusion

In this Kotlin Tutorial, we have learned how to handle the Kotlin Primary Constructor call expected – Compile Error by including the call to primary constructor using “this” keyword. Learn about Kotlin Secondary Constructor.