I want to do something like this:

interface Serializable<FromType, ToType> {
    fun serialize(): ToType
    companion object {
        abstract fun deserialize(serialized: ToType): FromType
    }
}

or even this would work for me:

interface Serializable<ToType> {
    fun serialize(): ToType
    constructor(serialized: ToType)
}

但两者都没有编译.Is there a syntax for this, or will I be forced to use make this an interface for a factory?或者还有其他答案吗?? 那太好了

推荐答案

Basically, nothing in a companion object can be abstract or open (and thus be overridden), and there's no way to require the implementations' companion objects to have a method or to define/require a constructor in an interface.

A possible solution for you is to separate these two functions into two interfaces:

interface Serializable<ToType> {
    fun serialize(): ToType
}

interface Deserializer<FromType, ToType> {
    fun deserialize(serialized: ToType): FromType
}

这样,您将能够实现类中的第一个接口,并使其companion object实现另一个接口:

class C: Serializable<String> {
    override fun serialize(): String = "..."

    companion object : Deserializer<C, String> {
        override fun deserialize(serialized: String): C = C()
    }
}

Also, there's a severe limitation that only a single generic specialization of a type can be used as a supertype, so this model of serializing through the interface implementation may turn out not scalable enough, not allowing multiple implementations with different ToTypes.

Kotlin相关问答推荐

这些Kotlin函数等效吗?

将文本与文本字段的内容对齐

Kotlin:将泛型添加到列表任何>

Scala与Kotlin中的迭代

数据流弹性模板失败,出现错误&未知非复合转换urn";

扩展属性委托给实例属性

为什么这两个 Kotlin 协程函数不一样?

使用 StateFlow 时如何移除监听器?

如何使用 Either monad 并避免嵌套 flatMap

为 Gradle 子项目配置 Kotlin 扩展

Kotlin 方法重载

如何禁用智能投射突出显示 Kotlin?

kotlin,如何从函数返回类类型

Hilt Activity 必须附加到 @AndroidEntryPoint 应用程序

Kotlin如何分派invoke操作符?

如何获取Kotlin中变量的名称?

如何在Kotlin中使用ViewModelProviders

具有泛型param的Kotlin抽象类和使用类型param的方法

Kotlin中默认导入哪些包/函数?

如何在 spring-boot Web 客户端中发送请求正文?