Reputation: 3694
Is there a any functional difference in Kotlin between those?
class Foo {
companion object {
fun newInstance() = Foo()
}
}
// Create new instance somewhere else
val foo = Foo.newInstance()
and
class Foo {
}
// Create new instance somewhere else
val foo = Foo()
I think that the first approach is just adding more boilerplate code and taking more memory because of companion object. Am I right?
Note: I am in Android environment and Foo
is actually an Fragment
in my case, if it matters.
Upvotes: 1
Views: 415
Reputation: 93581
There is no advantage to the first block of code in most cases.
However, in the case of Android Fragments, there is a pattern that you never use the constructor directly to create a Fragment. This is because the Android framework needs to be able to instantiate your Fragment on your behalf when it is recreating the Fragment, and it will only do this by using the empty (zero arguments) constructor. Therefore, when you need to pass arguments to a new Fragment, instead of creating a constructor for that, you create a factory function that creates the fragment with the empty constructor and then passes the arguments by adding them to the Fragment's bundle.
When you don't need any arguments passed to your new Fragment in this way, there's no actual need for the factory function instead of a constructor. However, some people do it that way anyway for consistency. Whether you want to follow this pattern is totally up to you.
Upvotes: 2
Reputation: 1256
At the documentation there is no need to companion objects https://developer.android.com/guide/fragments/create#kotlin
Upvotes: 1