I’m a long-time Java dev who is learning Kotlin.
Kotlin appears to be making a push for using top-level properties and functions, so I’m trying to get a feel for them. After some frustration, I have an insight that helps me think about top-level scope. I thought I’d share that insight – or at least present it for correction.
It seems that the top level scope is analogous to class scope. That is, I can expect visibility within the file to behave as if the contents of the file were wrapped in its own class.
Am I correct in this thinking? I’m trying to figure out how to think about files and top-level members so that I can properly design for them.
My frustration started with trying to create top-level factory methods for classes that should not be instantiated outside of the file. After all, I was supposed to be using top-level methods instead of static methods in Kotlin, where possible, right? I tried to make the class constructors private or protected and yet use them in the top-level methods. But that doesn’t work. I had to create a companion object for the factory methods instead.
How should I think about file scope in general? Thanks for your help!