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

Time:10-24

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

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?

CodePudding user response:

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
  • Related