Kotlin 在抽象类中调用伴生对象

Jul*_*lio 6 java kotlin

我有一个类,Base它是一个抽象类,定义为:

abstract class Base() {}
Run Code Online (Sandbox Code Playgroud)

我想从这个基类创建一些派生类:

class A : Base() {}
class B : Base() {}
class C : Base() {}
Run Code Online (Sandbox Code Playgroud)

我希望能够调用一个通用函数create来执行一些初始化工作并返回指定的派生类(例如A)。例如,像下面这样的东西是理想的:

val a = A.create() // `a` now holds an instance of `A`.
val b = B.create()
val c = C.create()
Run Code Online (Sandbox Code Playgroud)

最初,我尝试在抽象类中使用伴生对象作为一种静态函数:

abstract class Base {
    companion object {
        fun create() : Base { 
            // Do some initialization and return the derived class
            // of the object. Obviously I can't return `Base` as I've
            // indicated above since it is an abstract class. This is
            // what I'm confused about: How do I return a copy of the
            // _derived_ class here? Is this impossible? I think it
            // might be...
            return Base() // <-- This doesn't work. What should be returned?
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在派生类中:

class A : Base() {
    companion object {
        fun create() : A = Base.create()
    }
}
Run Code Online (Sandbox Code Playgroud)

由于显而易见的原因,这不起作用。也就是说,我无法返回抽象类的实例Base。有没有一种简单的方法来实现该var a = A.create()范式?派生类中的代码create是相同的,因此我想避免在我创建的每个类中重新创建功能。

Tpo*_*6oH 4

如果初始化逻辑相同并且基于类中指定的功能,Base您也可以这样做:

abstract class Base() {

    protected fun init(): Base {
        // do the initialization
        return this
    }
}

class A : Base() {
    companion object {
        fun create() = A().init() as A
    }
}
Run Code Online (Sandbox Code Playgroud)