What is the proper way to define constants in Kotl...
# getting-started
t
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
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
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
And when you want to access that constant like java in
public static final
way?
c
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
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
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