Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - Inheritance in Object expression

Tags:

android

kotlin

I need to inherit the Object A from Object B, were both the objects consist of constants only.

Example

 Object A {
  const val a1 = "some_data_1"
  const val a2 = "some_data_2"
 }

 Object B : A {
  const val b1 = "some_data_3"
 }

is it feasible to achieve this in kotlin ?

like image 957
Stack Avatar asked Jun 14 '26 12:06

Stack


1 Answers

Kotlin is an object-oriented programming (OOP) language. We can inherit object A from object B for that we have to to allow class "A" to be inherited, for that we need to attach the open modifier before the class to make it non-final.

For the const we have to use companion object, which is an object that is common to all instances of that class.

open class A {
     companion object {
        const val a1 = "some_data_1"
        const val a2 = "some_data_2"
     }
 }

class B : A() {
    companion object {
        const val b1 = "some_data_3"
    }
    val a_1 = a1
    val a_2 = a2
}

Check this link to understand inheritance

Check this link to understand Companion Object

like image 106
sourav Avatar answered Jun 17 '26 02:06

sourav