英文:
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<String>("A", "B", "C")
println(list::class) // => Prints "class java.util.Arrays$ArrayList"
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类的实例。
为什么?
- 可能以这种方式实现更容易/更快。(根据列表对象的类型,我们可以推断出
listof
只是在简单地调用java.util.Arrays.asList(...)
。) - 可能重新实现它没有优势;例如没有性能收益。
- 可能存在一些缺点;例如对那些需要使他们的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?
- 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 callingjava.util.Arrays.asList(...)
.) - There is possibly no advantage in reimplementing it; e.g. no performance benefit.
- 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论