How to put methods in companion object of parent class so that they can be inherited in children classes?

283 Views Asked by At

I have two data classes which are very similar to each other. I want to write a parent class for both of them so they can inherit the common functionality.

My problem is that some methods I want to inherit are needed to be inside companion object.

A) data class Link

import org.json.JSONArray
import org.json.JSONObject

data class Link(
    val name: String,
    val url: String
) {
    var selected: Boolean = false

    fun toggle() { selected = selected.not() }

    companion object {
        fun fromJson(obj: JSONObject): Link = with(obj) {
            Link(getString("name"), getString("url"))
        }

        fun fromJson(arr: JSONArray): List<Link> = with(arr) {
            List(length()) {
                fromJson(getJSONObject(it))
            }
        }

        fun toJson(list: List<Link>): JSONArray = JSONArray().apply {
            list.forEach {
                put(it.toJson())
            }
        }
    }

    fun toJson(): JSONObject = JSONObject().apply {
        put("name", name)
        put("url", url)
    }
}

B) data class DownloadStatus

import org.json.JSONArray
import org.json.JSONObject

data class DownloadStatus(
    val name: String,
    val url: String,
    val path: String,
    var progress: Int = 0
) {
    var selected: Boolean = false

    fun toggle() { selected = selected.not() }

    companion object {
        fun fromJson(obj: JSONObject): DownloadStatus = with(obj) {
            DownloadStatus(getString("name"), getString("url"), getString("path"), getInt("progress"))
        }

        fun fromJson(arr: JSONArray): List<DownloadStatus> = with(arr) {
            List(length()) {
                fromJson(getJSONObject(it))
            }
        }

        fun toJson(list: List<DownloadStatus>): JSONArray = JSONArray().apply {
            list.forEach {
                put(it.toJson())
            }
        }
    }

    fun toJson(): JSONObject = JSONObject().apply {
        put("name", name)
        put("url", url)
        put("path", path)
        put("progress", progress)
    }
}

abstract class Parent

abstract class Parent {
    var selected: Boolean = false

    fun toggle() { selected = selected.not() }

    companion object {

    }

    abstract fun toJson(): JSONObject
}

I am stuck here. How to put the methods in companion object of the parent class?

0

There are 0 best solutions below