``` fun bindView( position: Int, view: Lis...
# announcements
a
Copy code
fun bindView(
    position: Int,
    view: ListItemView // Interface
  ) = when (ViewTypeEnum.values()[position]) {
    ENUM1 -> bindViewType1(view as ViewType1)
    ENUM2 -> bindViewType2(view as ViewType2)
  }
a
@andreworobator What does the whole class look like?
l
Get rid of this enum and the
values()
call. It allocates a new array (defensive copy) each time you call it
a
Do you have an alternative for ensuring type safety? I’m willing to allocate a new array to ensure type safety because the performance hit is negligible.
a
we need more information to really give you a good solution. post the whole class for exampel
l
@andreworobator Actually, in this case, the performance hit may not be that negligible on a low end phone where you scroll very fast, because it is in a recyclerview that can bind a lot of items per seconds.
@andreworobator My recyclerview view types are not type safe, but it doesn't matter, I check by hand I handle it properly. It's all in one class, with only 2-3 usages after all.
a
@louiscad Thanks for the insight, you definitely don’t want to be doing allocations every time you’re binding a view. I’ve modified my code to avoid instantiating a new array every time.
Copy code
fun bindView(
  position: Int,
  view: ListItemView
) = when (ViewTypeEnum.values[position]) {
  ENUM1 -> bindViewType1(view as ViewType1)
  ENUM2 -> bindViewType2(view as ViewType2)
}

class ViewTypeEnum {
  ENUM1, ENUM2
  
  companion object {
    val values: Array<ViewTypeEnum> = ViewTypeEnum.values()
  }
}
l
@andreworobator I guess you meant
enum class
with a
;
after the last enum value
ENUM2
, but yes, such code is better. 👍 You could also add
@JvmField
to
values
😉
a
@louiscad The code I posted was a scrubbed down version to remove domain specific details. The real code compiles, I promise haha. This project is 100% kotlin so I don’t do interop code 🙂 Thanks again for the help!
😉 1
l
@andreworobator
@JvmField
is for performance, not for interop. You can make your enum class private BTW.
a
@louiscad How does
@JvmField
improve performance?
l
@andreworobator Saves a method call (getter), which still has a bit more overhead over a field access on dalvik VM or ART
💯 1
a
Awesome, thanks again @louiscad!
a
btw, your code is not typesafe, it can still fail at runtime without the compiler being able to tell you that you are doing something wrong