HarrisonQi
HarrisonQi

Reputation: 183

Kotlin data class cannot init attribute of Parent class

like this:

open class Father(
        val name:String = ""
)

data class Son(
        val age:Int = 1
):Father()

fun main(args: Array<String>) {
    val son = Son(
            name = "",
            age = 10
    )
}

I cannot init "name" attribute of Son because of it is from Parent Class Father. How can I fix this?

Upvotes: 1

Views: 239

Answers (1)

Sasi Kumar
Sasi Kumar

Reputation: 13288

It should be

open class Father(open val name: String="")

data class Son(val age: Int = 1,
override val name: String    ) : Father(name)

fun main(args: Array<String>) {
val son = Son(name = "",age = 10)
}

Upvotes: 2

Related Questions