https://kotlinlang.org logo
Title
a

andreworobator

04/06/2018, 6:42 PM
fun bindView(
    position: Int,
    view: ListItemView // Interface
  ) = when (ViewTypeEnum.values()[position]) {
    ENUM1 -> bindViewType1(view as ViewType1)
    ENUM2 -> bindViewType2(view as ViewType2)
  }
a

Andreas Sinz

04/06/2018, 6:56 PM
@andreworobator What does the whole class look like?
l

louiscad

04/07/2018, 8:28 AM
Get rid of this enum and the
values()
call. It allocates a new array (defensive copy) each time you call it
a

andreworobator

04/10/2018, 3:03 PM
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

Andreas Sinz

04/10/2018, 3:12 PM
we need more information to really give you a good solution. post the whole class for exampel
l

louiscad

04/10/2018, 3:25 PM
@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

andreworobator

04/10/2018, 3:49 PM
@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.
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

louiscad

04/10/2018, 3:51 PM
@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

andreworobator

04/10/2018, 3:54 PM
@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

louiscad

04/10/2018, 4:02 PM
@andreworobator
@JvmField
is for performance, not for interop. You can make your enum class private BTW.
a

andreworobator

04/10/2018, 4:10 PM
@louiscad How does
@JvmField
improve performance?
l

louiscad

04/10/2018, 4:13 PM
@andreworobator Saves a method call (getter), which still has a bit more overhead over a field access on dalvik VM or ART
💯 1
a

andreworobator

04/10/2018, 4:16 PM
Awesome, thanks again @louiscad!
a

Andreas Sinz

04/10/2018, 5:03 PM
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