1

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?

1 Answer 1

2

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)
}
Sign up to request clarification or add additional context in comments.

2 Comments

but there's too many classes like 'Son', this way make so many duplicate code....
Why do you need to override name in Son? It should work (more simply) without the override val, simply passing the parameter up to the superclass constructor.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.