Kotlin错误’未解决的引用’在尝试从Kotlin文件运行Java代码时出现

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

Kotlin Error 'unresolved reference' appears when trying to run Java Code from a Kotlin file

问题

当在Kotlin文件中使用Java代码时,如何引用Java类?

在Kotlin中使用Java代码时,需要确保以下几点:

  1. 确保Java类位于Kotlin文件的可见范围内,即Java类在Kotlin代码中可见。

  2. 导入Java类,以便Kotlin文件可以识别和使用它。

以下是一个示例,演示了如何在Kotlin文件中引用Java类Base32Decoder

import package.name.Base32Decoder  // 导入Java类

fun main(args: Array<String>) {
    val base32Decoder = Base32Decoder()  // 创建Java类的实例
    val rectangleArea: String = base32Decoder.base32Decode("JBSWY3DPFQQFO33SNRSCC===")
    println("inside the Kotlin codes:" + rectangleArea)
}

请确保将package.name替换为实际的Java类所在的包名。这样,您就可以在Kotlin文件中成功引用和使用Java类了。

英文:

Referencing Problem when Java Class is used in Kotlin. There is the Java class Base32Decoder.java and code from this class is used in the Kotlin file hello.kt.

When I try to run Java code through a Kotlin file, an error occurs because of no reference could be established to the Java class Base32Decoder.

Error message:

> hello.kt:4:25: error: unresolved reference: Base32Decoder

Base32Decoder Java class can't resolve the reference to it. Since this class is used inside the Kotlin file, the reference needs to work.

Code

fun main(args: Array&lt;String&gt;){
    val Base32Decoder = Base32Decoder()
   val rectangleArea: String = Base32Decoder.base32Decode(&quot;JBSWY3DPFQQFO33SNRSCC===&quot;)
   println(&quot;inside the Kotlin codes:&quot; + rectangleArea)
}

How can I reference Java classes when I want to use Java code in Kotlin files?

答案1

得分: 1

代码必须对Kotlin可访问。这意味着您需要编译(如果在终端中编译代码:javac SampleFile.java),以生成Base32Decoder.class文件。

现在在命令行中生成带有指向Kotlin文件的JAR文件:

jar cf app.jar Base32Decoder.class hello.kt

现在,由于您使用了kotlinc,您可以像这样在命令行中执行代码:

kotlinc -classpath app.jar -script hello.kt

现在您的代码应该能正常运行。问题在于Kotlin无法访问Base32Decoder.java类。

英文:

The code must be accessible for Kotlin. This means you have to compile (If you compile code in terminal: javac SampleFile.java The Base32Decoder.java file to generate the Base32Decoder.class.

Now generate the JAR-file with a link to the Kotlin file in command line:

jar cf app.jar Base32Decoder.class hello.kt

Now since you use kotlinc you can execute the code in command line like this:

kotlinc -classpath app.jar -script hello.kt

Now your code should run fine. The problem is that Kotlin didn't have access to the Base32Decoder.java class.

huangapple
  • 本文由 发表于 2023年6月1日 21:13:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76382285.html
匿名

发表评论

匿名网友

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

确定