简体   繁体   中英

Kotlin best practices: declare/init instance variables

Let's say I have the following classes:

class Activity1: Activity {
private var objects = arrayListOf<MyObject>()

  override fun onCreate(...) {
    ...
    Thread {
        getThoseObjects() {
            this.runOnUiThread {
                objects = it
                //load a fragment using objects
                val fragment = MyFragment.newInstance(objects)
            }
        }

    }.start()
  }

  fun startActivity2() {
    val i = Activity2.newIntent(objects)
    ...
  }
}

class Activity2: Activity {
  private lateinit var objects: ArrayList<MyObject>

  override onCreate(...) {
      objects = intent.getSerializableExtra(MY_KEY) as ArrayList<MyObject>
  }
}

Is this the accepted best practice for declaring/init-ing the objects arraylist in both of these classes?

In Activity1 I need to grab it from the server and use it in the fragment but also pass it to Activity2 if needed. I don't want to make it nullable but it also feels weird to init the empty array.

In Activity2, the lateinit var (from what I have found) seems like the best way to handle that.

As far as the unchecked cast from the getSerializableExtra cast, I'm confident that I can ignore the warning but I'd love it someone has a neat trick to avoid it.

You can also use lateinit var in the Activity1 for objects.

When you are sending the objects to the Activity2, Let the Activity2 handle the null values from the intent in onCreate method

You can use delegate property lazy for your initialization.

As per your scenario, you're having data from API (which means in future), and lazy block is use to make val initialization at invocation access, not at declaration.

So for Activity1, it'll be like:

private val objects by lazy { return@lazy arrayListOf<MyObject>()}

for Activity2:

private val objects: ArrayList<MyObject>? by lazy { return@lazy (intent?.getSerializableExtra(MY_KEY) as ArrayList<MyObject>) ?: null }

More from here .

Create some shared class/object like presenter with state, viewmodel or other abstraction depending on your architecture. It should be responsible for network call and storing value in field. Make request to load data in first activity. Then start second activity try to access field where value is stored(or not). If it not null show your data, if it isn't wait for it to complete and then notify your activity using some kind of observer pattern or other stuff. This is more clean way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM