Reputation: 278
I have a question about companion object in kotlin for Android: Instead of using extras or bundles, can I pass objects through companion object?
I've already tried this and it's work, but I don't know if this is a good method or should it be avoided?
EDIT: Thanks for yours answers, I suspected that was a bad practice but I wanted to be sure !
Upvotes: 0
Views: 1526
Reputation: 6363
Must be avoided, same as Java statics. Won't survive process recreation and introduces global mutable state.
Upvotes: 2
Reputation: 336
No it's bad practise to use the companion object as a object referencing tool. Please just add items to the bundle. I would recommand using the new Jetpack Navigation component if your using the bundle with fragment navigation. With the safeArgs it's really easy to navigate and pass objects.
Upvotes: 1
Reputation: 113
As it was said, passing objects through Companion object must be avoided, because it'd behave in the same way as Java statics.
The best option will be to pass your objects through bundles. If you don't like to implement Parcelable
on your own, you can try @Parcelize which is available in kotlin or some libraries, such as Parceler.
Upvotes: 2