转换为Kotlin后如何访问Java接口静态变量

时间:2018-10-24 12:41:13

标签: java kotlin

我有一个Java接口,带有一个静态变量interfaceValue,可以按以下方式访问

public class Experimenting {

    public interface MyInteface {
        int interfaceValue = 10;
    }

    class MyImpl implements MyInteface { }

    MyImpl myImpl = new MyImpl();

    void testing() {
        int getInterfaceValue = myImpl.interfaceValue;
    }
}

当我转换为Kotlin时,如下所示

class Experimenting {

    internal var myImpl = MyImpl()

    interface MyInteface {
        companion object {
            val interfaceValue = 10
        }
    }

    internal inner class MyImpl : MyInteface

    internal fun testing() {
        val getInterfaceValue = myImpl.interfaceValue
    }
}

但是myImpl.interfaceValue显示了编译错误符号,从而无法识别interfaceValue。我怎么仍可以在Kotlin中访问我的interfaceValue

2 个答案:

答案 0 :(得分:1)

该转换将static final interfaceValue转换为val Kotlins等效的companion。不幸的是,转换器并不完美,有时会搞砸。要访问它

import com.your.package.Experimenting.MyInteface.Companion.interfaceValue    
class Experimenting {

    internal var myImpl = MyImpl()

    interface MyInteface {
        companion object {
           const val interfaceValue = 10
        }
    }

    internal inner class MyImpl : MyInteface

    internal fun testing() {
        val getInterfaceValue = interfaceValue
    } 
}

起到了作用。

还可以:

class Experimenting {

    internal var myImpl = MyImpl()

    interface MyInteface {
        companion object {
           val interfaceValue = 10
        }
    }

    internal inner class MyImpl : MyInteface

    internal fun testing() {
        val getInterfaceValue = MyInteface.interfaceValue
    }
}

第三种方法是将interfaceValue的值复制到实现类中:

class Experimenting {

    internal var myImpl = MyImpl()

    interface MyInteface {
        companion object {
            const val interfaceValue = 10
        }
    }

    internal inner class MyImpl : MyInteface{
        val interfaceValue = MyInteface.interfaceValue
    }

    internal fun testing() {
        val getInterfaceValue = myImpl.interfaceValue
    }
}

基本上,您可以像访问Java中的静态变量一样对其进行访问。

答案 1 :(得分:0)

我想这种Java代码到Kotlin代码的正确转换应该如下

class Experimenting {

    internal var myImpl = MyImpl()

    interface MyInteface {

        val interfaceValue: Int
        get() = 10
    }

    internal inner class MyImpl : MyInteface

    internal fun testing() {
        val getInterfaceValue = myImpl.interfaceValue
    }
}

尽管它们在语法上有所不同,即interfaceValue不再是真正的静态变量,但实用性相同。