android - 使用 Kotlin Android 扩展的 when(view) 与 switch(view.getId())

标签 android kotlin 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 标识符的访问转换为一种使用哈希表实现的缓存。这可能需要比比较整数更繁重的工作,具体取决于实现。我完全支持可读的代码,但想更好地理解 KAE 的底层魔力。

考虑到这一点,

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

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 的整数比较会比整个对象的比较更好。

关于android - 使用 Kotlin Android 扩展的 when(view) 与 switch(view.getId()),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57746761/

相关文章:

android - 是否可以使用 XML 布局中的数据绑定(bind)访问为 TextView 编写的扩展函数?

android - 如何将 google charts 图形转换为 android 中的图像?

Android:在 View 区域外使用动画

android - viewpager setCurrentItem 不改变 tablayout 选择的颜色

android - 错误 : onActivityResult overrides nothing

oop - 安卓 : repository pattern what is the best solution to create an object?

Android - 即使将 kotlin 用作语言,Java 包名称也不会更改为 Kotlin

javascript - Android SQL 数据库文件未出现

java - "projections are not allowed for immediate arguments of a supertype"Kotlin Android Studio

android - Parcelize 在对象和枚举上提示 "Parcelable should be a class"