android51130
android51130

Reputation: 1115

Kotlin and jvm: object OR class instance?

object SampleObject{
   fun getSampleText(): String = "123"
}

class SampleClass {
   fun getSampleText(): String = "123"
}

There are no fields, methods only.

ActivityA starts ActivityB. In ActivityB there is a call to SampleObject.getSampleText() and SampleClass().getSampleText(). Then ActivityB finishes.

What is the best practice? To use object or to use class instances?

Upvotes: 0

Views: 174

Answers (1)

Mikezx6r
Mikezx6r

Reputation: 16905

If the function is pure (i.e. no side-effects), then code it at the top-level. No need to explicitly create a class/object in Kotlin.

The compiler will produce a class that contains your method as a static method, and therefore has the same lifecyle as all static methods.

An Object contains a static reference to a constructed version of itself, and the class has your function. Again, the class/method will exist for life of JVM

Upvotes: 1

Related Questions