美文网首页
kotlin中接口函数冲突问题

kotlin中接口函数冲突问题

作者: e小e | 来源:发表于2018-03-18 15:48 被阅读12次
interface B{
    fun x() : Int = 1
}

interface C{
    fun x() : Int = 0
}

open class A{
    fun x() : Int = 0
}

class D (val y : Int): A(),B,C{
    
}

如上这段代码,类D继承A实现B,C会造成函数x重写时候的冲突问题

class D (val y : Int): A(),B,C{
    //这里我并不知道到底是A,B,C中的哪个x()
    override fun x() : Int{

    }
}

所以我们需要解决这种情况通过如下方法

class D (val y : Int): A(),B,C{
    override fun x() : Int{
        if (y > 0){
            return y;
        }else if (y < 0){
            return super<B>.x();
        }else if (y < -100){
            return super<C>.x();
        }else{
            return super<A>.x();
        }
    }
}

相关文章

网友评论

      本文标题:kotlin中接口函数冲突问题

      本文链接:https://www.haomeiwen.com/subject/cqfeqftx.html