英文:
How is Kotlin able to call Java 11 code using JDK 1.8?
问题
我正在玩一个 Kotlin 项目,其中有一些 Java 11 的调用,但注意到它似乎可以使用 Java 8 来构建和运行。
特别的调用是 java.lang.String#isBlank()
,这是在 Java 11 中引入的。
我正在使用 Gradle 来构建和运行测试。构建的 JDK 设置为 JDK 1.8,而 Kotlin 的编译目标也是 1.8:
tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> {
kotlinOptions {
freeCompilerArgs += listOf("-Xjsr305=strict")
jvmTarget = "1.8"
}
}
gradle -v
------------------------------------------------------------
Gradle 6.6
------------------------------------------------------------
Build time: 2020-08-10 22:06:19 UTC
Revision: d119144684a0c301aea027b79857815659e431b9
Kotlin: 1.3.72
Groovy: 2.5.12
Ant: Apache Ant(TM) version 1.10.8 compiled on May 10 2020
JVM: 1.8.0_265 (AdoptOpenJDK 25.265-b01)
OS: Mac OS X 10.15.6 x86_64
这是一个单元测试,调用了 Java 11,但仍然能够编译和运行:
import org.junit.jupiter.api.Test
class BlankTest {
@Test
fun testBlank() {
val s = java.lang.String("test string")
val blank = s.isBlank()
println("Input string blank? : $blank")
}
}
这是如何可能的呢?
英文:
I was playing around with a Kotlin project which has some Java 11 calls and noticed that it seems to build and run fine using Java 8.
The call in particular is to java.lang.String#isBlank()
, which was introduced in Java 11.
I'm using Gradle to build and run tests. Build JDK is set to JDK 1.8 and Kotlin compile target is also 1.8:
tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> {
kotlinOptions {
freeCompilerArgs += listOf("-Xjsr305=strict")
jvmTarget = "1.8"
}
}
gradle -v
------------------------------------------------------------
Gradle 6.6
------------------------------------------------------------
Build time: 2020-08-10 22:06:19 UTC
Revision: d119144684a0c301aea027b79857815659e431b9
Kotlin: 1.3.72
Groovy: 2.5.12
Ant: Apache Ant(TM) version 1.10.8 compiled on May 10 2020
JVM: 1.8.0_265 (AdoptOpenJDK 25.265-b01)
OS: Mac OS X 10.15.6 x86_64
This is a unit test which calls Java 11 but still compiles and runs:
import org.junit.jupiter.api.Test
class BlankTest {
@Test
fun testBlank() {
val s = java.lang.String("test string")
val blank = s.isBlank()
println("Input string blank? : $blank")
}
}
How is this possible?
答案1
得分: 6
答案是,实际上你并没有使用 Java 11 的 isBlank()
方法,你在调用的是 Kotlin 的 isBlank 扩展函数,该函数可以应用于 java.lang.String。
英文:
The answer is that you're not actually using Java 11's isBlank()
method, you're calling Kotlin's isBlank extension function that can be applied to java.lang.String.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论