when(view) 与 switch(view.getId()) 与 Kotlin Android 扩展

when(view) vs. switch(view.getId()) with Kotlin Android Extensions

我对 Android 和 Kotlin 开发相当陌生,目前正在学习最初为 Java 编写的教程。在这些中经常出现这样的模式:

void onSomething(View v) {
  switch(v.getId()) {
  case R.id.btn1:
    ...
  }    
}

但是我在我的项目中使用 Kotlin 和 Kotlin Android 扩展,它允许编写这样的开关:

fun onSomething(v: View) {
  when (v) {
    btn1 -> { ... }
  }
}

最后一个对我来说似乎更具可读性,但据我了解,在幕后,KAE 将这个方便的 UI 标识符的访问转换为一种用哈希表实现的缓存。这可能需要 kinda 比比较整数更繁重的工作,具体取决于实现。我完全支持可读代码,但想更好地理解 KAE 的潜在魔力。

考虑到这一点,

1) 在开关中使用 View 引用而不是 ID 在 Kotlin / KAE 中是一种好的做法吗?

2) 除了过早的优化之外,它是否会潜在地以负面方式影响我的应用程序的性能或内存占用?

is using View references in switches instead of IDs a good practice in Kotlin / KAE?

嗯,when 语句在 Kotlin 中相当于 Java 的 switch 语句。

为了让您更加清楚,您没有理由不能这样做:

fun onSomething(v: View) {
    when (v.id) {//do a switch on the id instead of the entire object
        R.id.something -> { ... }
    }
}

回答您关于以下方面的问题:

could it potentially impact my app's performance or memory footprint in a negative way, premature optimization aside?

我认为这些都不会以您会注意到的方式或以实际重要的方式真正影响性能。如果非要我猜的话,我会说 id 的整数比较比整个对象的比较要好。