编译的kt文件是由字节码组成的?

时间:2017-09-28 12:12:49

标签: java kotlin

我试图了解编译的kotlin是否是java字节码文件。在这个例子中,我展示了kt文件和类文件,以及我不知道java中存在的某些关键字。例如,open val

编译的kt文件是否由字节码组成?编译的kt文件是否由JVM直接执行?

Greeting.kt

package org.jetbrains.kotlin.demo

data class Greeting(val id: Long, val content: String)

GrettingController.kt

@RestController
class GreetingController {

    val counter = AtomicLong()

    @GetMapping("/greeting")
    fun greeting(@RequestParam(value = "name", defaultValue = "World") name: String) =
            Greeting(counter.incrementAndGet(), "Hello, $name")

}

Greeting.class

public final data class Greeting public constructor(id: kotlin.Long, content: kotlin.String) {
    public final val content: kotlin.String /* compiled code */

    public final val id: kotlin.Long /* compiled code */

    public final operator fun component1(): kotlin.Long { /* compiled code */ }

    public final operator fun component2(): kotlin.String { /* compiled code */ }
}

GreetingController.class

@org.springframework.web.bind.annotation.RestController public open class GreetingController public constructor() {
    public open val counter: java.util.concurrent.atomic.AtomicLong /* compiled code */

    @org.springframework.web.bind.annotation.GetMapping public open fun greeting(@org.springframework.web.bind.annotation.RequestParam name: kotlin.String): org.jetbrains.kotlin.demo.Greeting { /* compiled code */ }
}

1 个答案:

答案 0 :(得分:3)

Kotlin没有被翻译成Java,而是直接编译成JVM字节码(*.class文件)。一些Kotlin语言结构实际上不能用Java表示。

为了方便阅读,您显示的已编译代码仅表示为Kotlin伪代码,并且使用存储在类文件中的其他Kotlin元数据。

来自Kotlin FAQ

  

Kotlin编译到什么地方?

     

当定位JVM时,Kotlin会生成Java兼容的字节码。当针对JavaScript时,Kotlin会转向ES5.1并生成与包括AMD和CommonJS在内的模块系统兼容的代码。当以native为目标时,Kotlin将生成特定于平台的代码(通过LLVM)。

另请参阅:how to view the bytecode when using IntelliJ IDEA

相关问题