Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use Object type vs straight Kotlin file

Tags:

android

kotlin

While working with Kotlin, I see you can define methods in a Kotlin file that has no class or object type (i.e. a file without class Test or object Test). I also see when you put methods into a Kotlin file without the class or object keywords, you need to import the method (i.e. import com.package.testMethod) to the file you want to use it. A little more context, I was trying to make some utility methods and started tinkering with both object and kotlin file with no class/object

My question is what is the use case for having a methods that aren't in some kind of object file? And when would you want to use this over something like object?

like image 358
jwenzel Avatar asked Jan 20 '26 18:01

jwenzel


1 Answers

You can either put your methods in the top-level declaration or inside an object. It's all about whether you want to pollute namespaces or not. You can have a function named X in an object and you can still have a function name X in a different object file since you can refer to specific method with the help of their object name. But you won't be able to do this if you declare methods top-level, each method would need to have a unique signature name(not counting overloaded methods).

Additionally, object can have supertypes, meaning you can inherit other classes or implement interfaces. Neither introduces more technical capability over another. If you define variables in an object or as top-level, both will be initialized lazily.

In short, it depends if you want to pollute namespaces or not.

like image 114
Taseer Ahmad Avatar answered Jan 22 '26 18:01

Taseer Ahmad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!