Kotlin接口中的伴侣对象 [英] Companion Objects in Kotlin Interfaces

查看:169
本文介绍了Kotlin接口中的伴侣对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将接口设为Parcelable,因此我需要这样的接口

I am trying to make a interface Parcelable, as such I need a interface like this

interface AB : Parcelable {
    companion object {
        val CREATOR : Parcelable.Creator<AB>
    }
}

我的两个班级A和B看起来像

and my two classes A and B looking like

data class A (...): Parcelable{
    ...
    companion object {
        val CREATOR : Parcelable.Creator<AB> = object : Parcelable.Creator<AB> {
            override fun newArray(size: Int): Array<AB?> {
                return arrayOfNulls(size)
            }

            override fun createFromParcel(parcel: Parcel): AB {
                return A(parcel)
            }

        }
    }

我正在努力在Kotlin中实现这样的接口.似乎接口类不允许使用CREATOR

I am struggling to implement such a interface in kotlin. It seems the interface class does not allow for the CREATOR

也许我采用了错误的方法,
我有一个包裹,其中包含A或B类的列表 所以我在做

Perhaps I am taking the wrong approach,
I have a parcelable that contains a list of classes that are either A or B so I am doing

parcel.readTypedList(this.list, AB.CREATOR)

我要求列表为A或B,这就是为什么我要使用接口.

I require that the list be either A or B and that is why I am using an interface.

有人有任何建议或可能的解决方案吗?

Anyone have any advice or a possible solution?

推荐答案

在Kotlin中,界面可以具有 companion object ,但它不是合同的一部分,必须由实现该接口的类来实现.它只是与具有一个单例实例的接口关联的对象.因此,它是一个可以存储事物的地方,但对实现类没有任何意义.

In Kotlin, an interface can have a companion object but it is not part of the contract that must be implemented by classes that implement the interface. It is just an object associated to the interface that has one singleton instance. So it is a place you can store things, but doesn't mean anything to the implementation class.

但是,您可以具有由类的companion object实现的接口.也许您想要更多类似这样的东西:

You can however, have an interface that is implemented by a companion object of a class. Maybe you want something more like this:

interface Behavior {
   fun makeName(): String
}

data class MyData(val data: String) {
    companion object: Behavior {  // interface used here
        override fun makeName(): String = "Fred"
    }
}

请注意,数据类未实现接口,但其companion object却实现了该接口.

Note that the data class does not implement the interface, but its companion object does.

A companion object对于存储与接口相关的常量或辅助函数很有用,例如:

A companion object on an interface would be useful for storing constants or helper functions related to the interface, such as:

interface Redirector {
    fun redirectView(newView: String, redirectCode: Int)

    companion object {
        val REDIRECT_WITH_FOCUS = 5
        val REDIRECT_SILENT = 1
    }
}

// which then can be accessed as:
val code = Redirector.REDIRECT_WITH_FOCUS

这篇关于Kotlin接口中的伴侣对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆