0

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 !

Ady
  • 230
  • 3
  • 16
  • This is not a good practice .. In this way all the properties you'll set will be static. Pass data in conventional way using `Bundle` ... – ADM Jun 20 '19 at 08:56
  • Yes you can. No you shouldn't because its bad practice – Rahul Jun 20 '19 at 10:15

3 Answers3

2

Must be avoided, same as Java statics. Won't survive process recreation and introduces global mutable state.

Miha_x64
  • 5,973
  • 1
  • 41
  • 63
2

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.

1

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.

Bram Jongebloet
  • 306
  • 1
  • 2
  • 10