The general pattern to create constants in Kotlin seems to be using companion objects. However, I can also define a constant at the file level. Why is that not so popular? A
I think that basically depends on whether you want that constant to be part of a class. If you put it inside a companion
object, it will be accessed like this:
Example.CONSTANT
If you choose to put a constant on file level, it will be imported from other files and accessed with simply CONSTANT
normally.
There are reasons for putting constants in classes as well as for putting them top-level.
Note that the const
keyword can only be applied to variables of type String
or primitive types (Int
etc.) (reference). For most cases though, there's no need to apply the keyword. Defining constant values as shown in the following works as well:
val constantFIS = FileInputStream("path")