Kotlin: Difference between constant in companion object and top level

Martin Tarjányi :

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? Am I missing something?

With companion object:

class Example {
    companion object {
        const val CONSTANT = "something"
}

On top level:

const val CONSTANT = "something"

class Example {
}
Marko Topolnik :

In Java you're forced to put all static field and method declarations in a class and often you even have to create a class just for that purpose. Coming to Kotlin, many users look for the equivalent facility out of habit and end up overusing companion objects.

Kotlin completely decouples the notions of a file and a class. You can declare any number of public classes is the same file. You can also declare private top-level functions and variables and they'll be accessible only to the classes within the same file. This is a great way to organize closely associated code and data.

Compared to top-level declarations, the syntax of companion objects is quite unwieldy. You should use them only when you specifically want to associate some public static code or data with a class and want your users to qualify access to it with the class's name. The use cases for this are quite rare and in most cases the top-level declarations are more natural.

Whenever you have some private static code/data that you want to couple to a class, you'll be better served with private top-level declarations.

Finally, sometimes the concern of the generated bytecode matters. If, for whatever reason, you have to produce a Java class with Kotlin code such that the class has a static member, you must resort to a companion object and a special annotation.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Kotlin: Difference between object and companion object in a class

difference between fun in companion object block and outside of class in kotlin?

Difference between primitive companion constants and java wrapper constant

what's the difference between val and const val in companion object?

What's the difference between a companion object and a singleton class in Scala (Guice)

Scala what is the difference between defining a method in the class instead on the companion object

Difference between instantiating something from the class and from the companion object

Difference between a class and object in Kotlin

Companion object with extension function in kotlin?

Restricting type of companion object in Kotlin

Kotlin - Companion Object with Receiver Function

Kotlin companion object unexpected result

kotlin companion object field with debugger

Mocking companion object function in kotlin

Kotlin - attribute visibility to companion object

What's the difference between top-level edges and top-level nodes?

Kotlin - Difference between var vs object declaration

What is difference between object and data class in Kotlin?

Kotlin - What does companion object fun do?

Kotlin Calling Companion Object in Abstract Class

How to override kotlin interface inside companion object

Generics in Kotlin: how to access companion object

Kotlin shared companion object across junit tests

Confused about Kotlin's companion object definition

Kotlin - Cant init a companion object value

How to access Kotlin companion object in Java?

Kotlin Extension on a class without Companion object

Kotlin Companion Object - Init Block - Typealias

Kotlin static functions : companion object, @JvmStatic @JvmField

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive