本文介绍了Kotlin:一个抽象超类可以有一个抽象构造函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚写了这篇,目前为止还不错:

I have just written this, which is fine as far as it goes:

import com.github.salomonbrys.kotson.get
import com.github.salomonbrys.kotson.int
import com.github.salomonbrys.kotson.jsonObject
import com.google.gson.JsonElement
import com.google.gson.JsonObject

abstract class BatchJobPayload {
    abstract fun toJson(): JsonObject
}

class BookingConfirmationMessagePayload(val bookingId: Int) : BatchJobPayload() {
    constructor(payload: JsonElement) : this(payload["bookingId"].int)

    override fun toJson() = jsonObject(
        "bookingId" to bookingId
    )
}

但是,我想坚持认为,如果可能的话,所有扩展BatchJobPayload的类都应实现带有签名的辅助构造函数.constructor(payload: JsonElement): BatchJobPayload,用于反序列化.

But I'd like to insist, if possible, that all classes that extend BatchJobPayload implement a secondary constructor with the signatureconstructor(payload: JsonElement): BatchJobPayload, which is to be used for deserializing.

BookingConfirmationMessagePayload具有这样的构造函数,但这只是因为我将其放在那里,而不是因为BatchJobPayload坚持使用了它……

BookingConfirmationMessagePayload has such a constructor but only because I put it there, not because BatchJobPayload insisted upon it...

推荐答案

您不能强制执行超级构造函数,但是可以让工厂执行强制执行的spawn方法,该方法会返回BatchJobPayload的子类,从而使您可以确保类是可构造的.

You can't enforce a super constructor, but you can have factories with a spawn method enforced that returns a subclass of BatchJobPayload, which allows you to make sure classes will be constructable.

它看起来像这样:

class JsonObject // Included to make compiler happy

abstract class Factory<T> {
    abstract fun make(obj: JsonObject): T
}

abstract class Base {
    abstract fun toJson(): JsonObject
}


class A(val data:JsonObject):Base() {
    override fun toJson(): JsonObject {
        return JsonObject()
    }
}

class AFactory: Factory<A>() {
    override fun make(obj: JsonObject): A {
        return A(obj)
    }

}

fun main(args: Array<String>) {
    val dummyJson = JsonObject()

    var factory = AFactory()
    var instance = factory.make(dummyJson)

    println(instance)
}

这篇关于Kotlin:一个抽象超类可以有一个抽象构造函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 06:36