for classes without properties and without constru...
# getting-started
y
for classes without properties and without constructors, should I always prefer
object
over
class
?
t
If it doesnt hold any state I would say objects show intent better (there should only be 1 instance)
🫡 1
j
JetBrains also encourages you to use objects instead of empty classes when creating a sealed class
đź‘Ť 2
s
of course functions are first class in Kotlin, so there's the alternative of simply using top-level functions. The object in your case is basically only a namespace anyways.
e
I wouldn't say "always"; there are some use cases for "empty" yet non-singleton classes. but usually you don't need them
g
One could ask: why use a class at all? If it is just a container for functions, you can put functions directly in files without any container.
y
because as @Stephan Schröder said, objects can be seen as a Kotlin workaround for namespaces. you may not want everything at the top level (I don’t)
and you’ve got state, then not using a class is a non-starter
g
I would not agree to that without know the concrete case. Having a data store on top level in a package or publicly available in an object is no big difference.
y
it’s useful for code organization (grouping related functions together makes them easier to refactor out, unless you don’t care about having a large amount of small source code files) there is also a difference in call semantics (
ObjectName.function()
vs
function()
) which helps signaling intent
e
no, there isn't, since you can
import ObjectName.function
y
right, but you have the option to do this.