Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Primary constructor call expected

Tags:

kotlin

this is example of inheritance in Kotlin.

open class Person() {
    var _name : String = ""
    var _age : Int = 0

    constructor(name: String, age : Int)  : this(){
        _name = name
        _age = age
    }
}

class Student() : Person() {
    var _university : String = ""

    constructor (name : String, age: Int, university: String) : super(name, age){
        _university = university
    } 
}

fun main() {
   var person = Person("a", 10)
   var student = Student("b", 18, "MIT")
   println("${person._name} : ${person._age}")
   println("${student._university}")
}

How can I resolve error "Primary constructor call expected" in this case?

like image 753
quangdien Avatar asked Aug 29 '26 18:08

quangdien


1 Answers

If a class has a primary constructor, you must delegate the secondary constructors to the primary. Which is the case for Student class which is not doing so.

First you should remove the boilerplate of Person class following Kotlin's idioms (using optional parameters rather than constructor overloading).

// This one's completely optional to do, skip if you don't want to follow idioms
open class Person(
    var name : String = ""
    var age : Int = 0
)

And then Student class should have two separate constructors, because if you take a primary constructor then other constructors must delegate to it:

class Student: Person {
    var university: String = ""
    
    constructor() : super()

    constructor (name: String, age: Int, university: String) : super(name, age) {
        this.university = university
    }
}
like image 94
Animesh Sahu Avatar answered Sep 02 '26 00:09

Animesh Sahu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!