user2211907
user2211907

Reputation:

How to get both static and instance access to a classes field

Suppose I have an abstract superclass A. That class has a property abstract val predicate: (ModelClass) -> Boolean.

Let B be a subclass.

I want to be able to do both of the following:

How can I do this.

Upvotes: 1

Views: 63

Answers (2)

goedi
goedi

Reputation: 2083

Does your class need to be abstract? Maybe the code below can be useful:

open class MyClass {
    companion object myCompanion {
        val myStatic = "MyClass"
    }
    open val myStatic = myCompanion.myStatic
}

class MySubClass : MyClass() {
    companion object myCompanionSubClass {
        val myStatic = "MySubClass"
    }
    override var myStatic = myCompanionSubClass.myStatic
}

fun main() {
    println(MyClass.myStatic)
    val t = MyClass()
    println(t.myStatic)

    println(MySubClass.myStatic)
    val subClass = MySubClass()
    println(subClass.myStatic)
}

In this code you can define a static property and use it from the class or any instance. It is also possible to override the property in a subclass and use it in the same way.

Upvotes: 0

Quinn
Quinn

Reputation: 9434

I don't think this is possible.

There is no such thing as an abstract static method in Kotlin or Java.

Perhaps this will give more insight.

Upvotes: 1

Related Questions