为什么我可以在Kotlin中省略函数调用?

在下面的例子中,我有2个函数,返回int。 在一种情况下,我有义务使用函数调用括号() ,在其他情况下,我被禁止使用它。

为什么以及如何控制?

 package kotlin.tests import java.util.ArrayList object MyObject { fun getValue(): Int { return 0 } } fun main() { val arrayList : ArrayList = ArrayList() println(arrayList.size()) // Expression 'size' of type 'Int' cannot be invoked as a function. The function 'invoke()' is not found println(MyObject.getValue) // Function invocation 'getValue()' expected } 

sizeList接口上的一个属性,而不是一个函数。 这就是为什么你可以(必须)访问它没有括号。

Kotlin使用一些编译器魔术来将 自己的集合types 映射到JVMtypes。 他们只是决定把集合的大小作为一个属性公开,每当你在Kotlin中使用集合时,即使它们的底层实现是java.util.ArrayList类,你也可以通过Kotlin定义的接口来看到它们。