Kotlin接口在Java类中不可访问。

huangapple go评论67阅读模式
英文:

Kotlin interface in not accessible from Java class

问题

我在 Kotlin 上创建了一个接口。

interface IDataManager{
    val dataType: String?
}

现在我正试图在我的 Java 类中获取它的变量,如下所示。

public static DataWrapper getInstance(IDataManager iDataManager) {
    String dataType = iDataManager.getDataType();
    return instance;
}

但我得到了一个错误:error: cannot find symbol iDataManager.getDataType()

英文:

I have created an interface on kotlin.

interface IDataManager{
    val dataType: String?
}

Now I am trying to get its variable in my java class, like following.

public static DataWrapper getInstance(IDataManager iDataManager) {
    dataType= iDataManager.dataType;
    return instance;
}

But I am getting error: cannot find symbol iDataManager.dataType

答案1

得分: 3

请调用 getter 函数以获取变量的值:

dataType = iDataManager.getDataType();

如果我们在 Kotlin 一侧使用属性,我们应该在 Java 一侧使用 gettersetter 来访问这些属性。

英文:

Please call getter function to get a value of the variable:

dataType = iDataManager.getDataType();

If we use properties on Kotlin side we should use getters and setters to access those properties on Java side.

答案2

得分: 0

编辑 - 正如Alexey在评论中指出的那样,这对于接口是不起作用的,因为属性需要有支持字段,而接口中的属性无法拥有这些。这仍然是有用的信息,但不适用于提问者的问题

除了Sergey说的内容之外,如果你想将某些内容作为字段公开,而不是生成getter和setter,你还可以在这些内容上添加@JvmField注解。

interface IDataManager {
    @JvmField val dataType: String?
}

另一个有用的注解是@JvmStatic,用于与Java互操作,你可以将它放在伴生对象中的属性和函数上,这样就不需要像这样:

Utils.Companion.coolUtility()

而可以像你习惯的这样写:

Utils.coolUtility()
英文:

edit - as Alexey points out in the comments, this doesn't work for interfaces, since the property needs a backing field and properties in interfaces can't have those. It's still useful to know, but it doesn't apply to the OP's question

As well as what Sergey said, you can add the @JvmField annotation on things if you want to expose them as a field instead of generating the getters and setters

interface IDataManager{
    @JvmField val dataType: String?
}

@JvmStatic is another useful one for Java interop, you can put it on properties and functions in companion objects, so instead of this

Utils.Companion.coolUtility()

you can do this (like you're used to)

Utils.coolUtility()

huangapple
  • 本文由 发表于 2020年9月24日 03:02:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/64034684.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定