Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I avoid a "Primary constructor call expected" in this case?

I’ve created a Person class and a Student class here in Kotlin:

In line 27, I’m trying to achieve a case where a user can create a "Student" class by providing 4 parameters: FirstName, LastName, Age, and Degree.

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’ve also written the equivalent code in Java. I’m trying to achieve the Java equivalent code’s Secondary Constructor in line 30:

enter image description here

How can I avoid a "Primary constructor call expected" in the Kotlin code?

>Solution :

For your use case you don’t even need secondary constructors. You could have optional arguments in the constructor. Like this for example:

open class Person(var firstName: String, var lastName: String, var age: Int? = null) {
    override fun toString() = "$firstName | $lastName | $age"
}

class Student(firstName: String, lastName: String, var degree: String, age: Int? = null) : Person(firstName, lastName, age) {
    override fun toString() = "$firstName | $lastName | $age | $degree"
}

To demonstrate:

fun main() {
    val a = Person("Aaa", "aaA")
    val b = Person("Bbb", "bbB", 20)
    val c = Student("Ccc", "ccC", "degreeC")
    val d = Student("Ddd", "ddD", "degreeD", 21)

    println(a)
    println(b)
    println(c)
    println(d)
}

Output:

Aaa | aaA | null
Bbb | bbB | 20
Ccc | ccC | null | degreeC
Ddd | ddD | 21 | degreeD
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading