Reputation: 961
I'm new to Kotlin. And I'm struggling with inheritance. Consider the following case.
This code is ok
open class BaseClass(
val property1: String,
val property2: String,
)
And this one also
data class ExtendedClass(
val propety3: String
): BaseClass()
But here we have a compilation problem
val extended = ExtendedClass(
property1 = "",
property2 = "",
property3 = ""
)
What is the use of open class inheritance if it's prohibited to construct sub-classes in that way? Instead I have to do something like
val extended = ExtendedClass(property3 = "")
extended.property1 = "",
extended.property2 = ""
But that trick kills immutability.
Upvotes: 2
Views: 1419
Reputation: 13284
You may want to declare the BaseClass
as abstract and inherith its properties in the ExtendedClass
:
abstract class BaseClass {
abstract val property1: String
abstract val property2: String
}
class ExtendedClass(
override val property1: String,
override val property2: String,
val propety3: String
) : BaseClass()
You can then initialize the ExtendedClass
with the 3 immutable properties:
val extendedClass = ExtendedClass(
property1 = "Property 1",
property2 = "Property 2",
property3 = "Property 3"
)
Upvotes: 1