英文:
Kotlin Error 'unresolved reference' appears when trying to run Java Code from a Kotlin file
问题
当在Kotlin文件中使用Java代码时,如何引用Java类?
在Kotlin中使用Java代码时,需要确保以下几点:
-
确保Java类位于Kotlin文件的可见范围内,即Java类在Kotlin代码中可见。
-
导入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<String>){
val Base32Decoder = Base32Decoder()
val rectangleArea: String = Base32Decoder.base32Decode("JBSWY3DPFQQFO33SNRSCC===")
println("inside the Kotlin codes:" + 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论