Using an Object Method vs Using a Custom Getter in Accessing Array Size


#1

What is the best way to access a dynamic value like an array size inside a class? In Java, I would create a getSize() function that would return the size of the array. In Kotlin, there are two ways of doing this:

// One solution
val size get() = myArray.size

// Another solution
fun size() = myArray.size

Is one method preferable than the other?


#2

According to the Kotlin Coding Conventions one should prefer a function to a property if the size of ‘myArray’ could vary between calls and therefore violate the fourth condition.


#3

returns the same result over invocations

@alanfo I don’t think it should be interpreted so strict that the property couldn’t vary between calls at all. For a class with mutable state it should return the same result if its state is unchanged.


#4

Well, I agree that the fourth condition seems too strict, but that’s what the words say.

Perhaps the next time the code is revised it could be changed to something similar to what you’ve just said.