Kotlin: Difference between constant in companion object and top level

前端 未结 3 1348
情深已故
情深已故 2020-12-14 00:07

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

3条回答
  •  时光取名叫无心
    2020-12-14 00:48

    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")
    

提交回复
热议问题