Why can I omit function invocations sometimes in Kotlin?

315 views Asked by At

In the following example I have 2 functions, returning int. In one case I am obliged to use function invocation brackets (), in other case I am prohibited to use it.

Why and how to control?

package kotlin.tests

import java.util.ArrayList

object MyObject {
    fun getValue(): Int {
        return 0
    }
}


fun main() {

    val arrayList : ArrayList<Any> = 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

}
1

There are 1 answers

3
zsmb13 On BEST ANSWER

size is a property on the List interface, and not a function. That's why you can (have to) access it without parentheses.

Kotlin uses some compiler magic to map its own collection types to the JVM types. They just decided to expose the size of collections as a property for some reason, and every time you use collections in Kotlin, even though their underlying implementations are classes like java.util.ArrayList, you see them through the interfaces defined by Kotlin.