为什么 Kotlin 集合的运行时类是 Java 类?

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

Why is the run-time class of a Kotlin-collection a Java-class?

问题

在JetBrains的Coursera上的《面向Java开发者的Kotlin课程》中,介绍了Kotlin代码会直接编译成字节码。然后这个字节码会在JVM上执行。

但是当我这样做时:

var list = listOf<String>("A", "B", "C")
println(list::class) // => 输出 "class java.util.Arrays$ArrayList"

显然正常的Java ArrayList 在底层被使用。所以我感到困惑...

Kotlin只是一种“更现代”的语法吗,它在底层使用Java?

实际上它是一些语法糖,封装在上面,以更优雅的方式编写代码。但在底层仍然是同样的旧Java东西。

英文:

In the "Kotlin for Java-Developers"-course by JetBrains (at Coursera) it is told, that Kotlin-code is compiled to byte-code directly. And that byte-code is then executed on the JVM.

But when I do:

var list = listOf&lt;String&gt;(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;)
println(list::class) // =&gt; Prints &quot;class java.util.Arrays$ArrayList&quot;

Obviously the normal Java ArrayList is used underneath. So I confused ...

Is Kotlin just some "more modern" syntax thing, which uses Java underneath?

Practically some syntactic sugar, which is put on-top, so that one can write code in a nicier way. But underneath it's still the same old Java-thing.

答案1

得分: 5

Kotlin只是一种使用Java作为基础的“更现代”语法吗?

不是。你的Kotlin源代码会被编译成字节码。

但是你的代码正在使用listof Kotlin库函数,而该函数的实现返回的是一个Java类的实例。

为什么?

  1. 可能以这种方式实现更容易/更快。(根据列表对象的类型,我们可以推断出listof只是在简单地调用java.util.Arrays.asList(...)。)
  2. 可能重新实现它没有优势;例如没有性能收益。
  3. 可能存在一些缺点;例如对那些需要使他们的Kotlin代码与使用标准Java集合类的Java互操作的人可能会造成问题。
英文:

> Is Kotlin just some "more modern" syntax thing, which uses Java underneath?

No. You Kotlin source code >>is<< compiling to bytecodes.

But your code is using the listof Kotlin library function, and the implementation of that function is returning a value that is an instance of a Java class.

Why?

  1. It was probably easier / quicker to implement it that way. (Based on the type of the list object, we can infer that listof is simply calling java.util.Arrays.asList(...).)
  2. There is possibly no advantage in reimplementing it; e.g. no performance benefit.
  3. There are possibly disadvantages; e.g. it is likely to cause problems for people who need their Kotlin code to be interoperable with Java which uses standard Java collection classes.

huangapple
  • 本文由 发表于 2020年5月2日 14:31:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/61555389.html
匿名

发表评论

匿名网友

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

确定