I’m a new Kotlin dev switched from Java. I have many Helper/Util classes in my project which can have up to 20 methods in some. In Java I used to set the functions as public static and I understand that companion object works the same way in Kotlin.
However I find that calling the methods using instantiate is similarly easy to manage and I don’t have to place the methods in companion object. I recently realised that using this way all the time might be risky performance wise(?) and thought it’d be good to ask here. So is instantiating an acceptable way to call methods from other classes?
ConversionHelper
class ConversionHelper {
fun convertTemperature(value: Int) {
//code...
}
fun convertPressure(value: Int) {
//code...
}
}
SomeActivity
class SomeActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
//code...
val tempValue = 26
val pressureValue = 300
val displayTemperature = ConversionHelper().convertTemperature(tempValue)
val displayPressure = ConversionHelper().convertPressure(pressureValue)
}
}
In my search for this answer, I learned that declaring the Helper/Util classes as Object is a good way to do this as well so I’ll be considering it. But for other classes is above an acceptable way to go about it?
hashesofdreams is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
0
That is ugly, obtuse code. It does affect performance, but not significantly unless you’re doing it inside a big loop iteration.
You can simply create object
classes. No need for companion object
s if your utility functions aren’t associated with a class you actually need to create instances of.
object ConversionHelper {
fun convertTemperature(value: Int) {
//code...
}
fun convertPressure(value: Int) {
//code...
}
}
Even if object
classes didn’t exist, it would be far preferable to use companion objects over forcing a useless class to be instantiated just to call a helper function. That is basically forcing you to write code that looks like nonsense.
2
So that works, but you’re creating a lot of unneeded objects. There’s a few better ways:
Method 1: Don’t make them class methods. In Kotlin, unlike Java, methods can exist outside any class. So just make them at file scope:
fun convertTemperature(value: Int){}
Method 2: Make them static functions on the object. To do this:
class ConversionHelper {
companion object {
fun convertTemperature(value: Int) {
//code...
}
}
}
It can then be called via ConversionHelper.convertTemperature(value)
1