简体   繁体   English

Kotlin最佳做法:声明/初始化实例变量

[英]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? 这是在这两个类中声明/初始化对象arraylist的公认最佳实践吗?

In Activity1 I need to grab it from the server and use it in the fragment but also pass it to Activity2 if needed. 在Activity1中,我需要从服务器中获取它,并在片段中使用它,还可以在需要时将其传递给Activity2。 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. 在Activity2中,lateinit var(根据我的发现)似乎是处理该问题的最佳方法。

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. 至于getSerializableExtra强制转换中未经检查的强制转换,我相信我可以忽略该警告,但我希望它有人可以巧妙地避免它。

You can also use lateinit var in the Activity1 for objects. 您还可以在Activity1中为对象使用lateinit var。

When you are sending the objects to the Activity2, Let the Activity2 handle the null values from the intent in onCreate method 将对象发送到Activity2时,让Activity2处理onCreate方法中意图的空值

You can use delegate property lazy for your initialization. 您可以使用委托属性lazy进行初始化。

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. 根据您的方案,您正在从API获取数据(这意味着将来),并且惰性块用于在调用访问而不是声明时进行val初始化。

So for Activity1, it'll be like: 因此,对于Activity1,它将类似于:

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

for Activity2: 对于活动2:

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. 根据您的架构,使用状态,视图模型或其他抽象来创建一些共享的类/对象,例如presenter。 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. 如果不为null,则显示您的数据;如果不等待数据完成,则使用某种观察者模式或其他方式通知您的活动。 This is more clean way. 这是更干净的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 Kotlin class 中声明值的最佳方式:在 Constructor、body 或 init{} - Best way to declare value in Kotlin class : in Constructor, body or init{} 最佳实践 - 声明opengles 2.0立方体顶点 - Best practices - Declare opengles 2.0 cube vertices Kotlin onClick 事件和架构最佳实践 - Kotlin onClick events and architecture best practices 声明一堆可绘制对象(Kotlin)的最佳方法是什么? - What is the best way to declare a bunch of drawables (Kotlin)? Android - Gradle构建脚本中变量的最佳实践 - Android - Best practices for variables in Gradle build script 从Firebase更新应用中变量的最佳做法 - Best practices to update variables in app from firebase Kotlin中的init方法取决于变量的顺序和init方法的声明 - init method in kotlin dependent on order of variables and init method declaration 使用全局变量或将方法参数传递给方法变量的最佳实践? - Best Practices Using Global Variables or Passing Method Arguments to Method Variables? 使用Kotlin在Android上的UI组件上声明的最佳方法是什么? - What is the best way to declare on UI component in android with Kotlin? 如何在 Kotlin 中声明变量? 我收到“未解决的参考” - How to declare variables in Kotlin? I'm getting "Unresolved Reference"
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM