为什么Kotlin使用诸如arrayOf之类的全局函数 [英] Why does Kotlin use global functions like arrayOf
问题描述
我是Kotlin的新手.我发现这是一种怪异的做法.
I'm new to Kotlin. I find this to be a weird practice.
在arrayOf
/mutableListOf
的情况下,本能是尝试使用构造函数(即new Array<T>(...args)
)尝试这些类型之一的 construct .甚至是静态工厂方法,例如LocalDateTime.of(...)
.
With the case of arrayOf
/ mutableListOf
, the instinct is to try a construct one of these types using a constructor, i.e. new Array<T>(...args)
. Or even a static factory method, like i.e. LocalDateTime.of(...)
.
为什么不使用new Array<T>()
,或者至少不使用范围函数,即Array.of
.这些方法也不会使全局范围杂乱无章吗?
Why wasn't new Array<T>()
used, or at least a scoped function, i.e. Array.of
. Don't these methods also clutter the global scope?
推荐答案
arrayOf
和mutableListOf
不在全局范围"内(甚至不存在).它们分别位于kotlin
和kotlin.collections
软件包中.
arrayOf
and mutableListOf
are not in "global scope" (that's not even something that exists). They're in the kotlin
and kotlin.collections
packages, respectively.
kotlin.*
和kotlin.collections.*
恰好是任何kotlin文件的默认导入,因此您不必自己进行该导入.请参见默认导入.
It just so happens that kotlin.*
and kotlin.collections.*
are default imports of any kotlin file, so you don't have to make that import yourself. See Default Imports.
这类似于Java,其中默认情况下会导入java.lang.*
,而无需指定它.
This is similar to Java where java.lang.*
is imported by default and you don't need to specify it.
此外,您不能构造" arrayOf和mutableListOf,因为它们不是类型.它们是方法-实际上,它们以小写字母开头是表明类型的标准方式-类型以大写字母开头.
Also, you can't "construct" arrayOf and mutableListOf because they're not types; they're methods - and the fact the they start with a lowercase letter is the standard way to indicate that - types start with uppercase letters.
Kotlin允许类级别以外的程序包级别的方法(尽管为JVM编译时,它们将位于类内部),但这与Java中的import static
并没有太大区别,在Java中,import static
可以从其中访问静态方法.没有类名作为前缀的类.
Kotlin allows methods at package level outside a class (although when compiled for the JVM, they will be inside a class), but that's not very different from an import static
in Java with which you can access a static method from a class without the classname as a prefix.
这篇关于为什么Kotlin使用诸如arrayOf之类的全局函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!