1

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:

  • Use the predicate from an instance aInstance.predicate
  • Also use that predicate elsewhere, without having to create an instance to get that predicate B.predicate

How can I do this.

  • Does this answer your question? [What is the equivalent of Java static methods in Kotlin?](https://stackoverflow.com/questions/40352684/what-is-the-equivalent-of-java-static-methods-in-kotlin) – IR42 Mar 11 '20 at 18:20
  • @DrawnRaccoon I don't think that does answer this question – Quinn Mar 11 '20 at 18:22
  • @DrawnRaccoon I know about companion objects, but I don't know how to define the superclass so that both subclasses' companion objects are required to have the same function which can be overriden. –  Mar 11 '20 at 18:24

2 Answers2

1

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.

Quinn
  • 7,072
  • 7
  • 39
  • 61
  • 1
    Probably this sentence explains it pretty well: _Because "abstract" means: "Implements no functionality", and "static" means: "There is functionality even if you don't have an object instance". And that's a logical contradiction_ – ich5003 Mar 11 '20 at 18:31
  • I rewrote my question to explain what I am trying to do rather than suggestion a specific solution. –  Mar 11 '20 at 18:33
  • Even with your rewritten question this does not work. You cannot have an abstract value which is also static. So either it is abstract and depends on an object or it is static and depends on a class. – ich5003 Mar 11 '20 at 18:38
0

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.

Diego Marin Santos
  • 1,923
  • 2
  • 15
  • 29