https://kotlinlang.org logo
t

Tara Czutno

06/09/2023, 11:12 PM
What is the proper way to define constants in Kotlin? Top of the file like:
Copy code
private const val NUM_THREADS = 15
OR Bottom of the file like:
Copy code
companion object {
        const val RECENT_ACTIVITY_LIMIT = 10
    }
j

Joffrey

06/09/2023, 11:15 PM
It mostly depends on whether you want the access to the constant to be with a namespace. For private constants I usually leave them at the top level
👍 2
s

Stefan Oltmann

06/10/2023, 4:13 AM
I mostly use the companion object because I don’t like how IDEA displays it as a kt-File instead a Kotlin Class otherwise. 👀 Something is wrong with me. 😅
same 5
h

Humphrey

06/10/2023, 6:56 AM
And when you want to access that constant like java in
public static final
way?
c

Charles Flynn

06/10/2023, 8:15 AM
If the file is a class (e.g. a spring component) then I'm like @Stefan Oltmann I'll put it in the companion object so intellij shows it as a class file. Otherwise top level is fine. It doesn't really matter and it's the sort of thing at code review I don't insist on a standard.
1
j

Joffrey

06/13/2023, 3:21 PM
And when you want to access that constant like java in public static final way?
I somehow missed this, I guess that was a question for me. In that case I use the companion object (if an existing class makes sense to hold that constant), or I create a standalone
object
with a relevant name to hold the constant(s).
👍 1
h

Humphrey

06/13/2023, 3:24 PM
Normally I would like to use the same class to hold that object but I’ve seen people mentioning to create a separate class to hold those constants. I would like to use it like MyObject.CONSTANT
2 Views