https://kotlinlang.org logo
#getting-started
Title
# getting-started
y

y

02/25/2024, 1:26 PM
given
Copy code
enum class Bar {
  ONE,
  TWO,
}
and
Copy code
enum class Foo {
  A,
  B,
  C,
  ;
  val asBar get() = 
    when (this) {
      A, B -> Bar.ONE,
      C -> Bar.TWO,
    }
}
vs.
Copy code
enum class Foo(val asBar: Bar) {
  A(Bar.ONE),
  B(Bar.ONE),
  C(Bar.TWO),
}
the second one compiles to something shorter, so is it the preferred way to write this? specifically, is it also "zero sized" (whatever that term would mean in JVM land)?
j

jamshedalamqaderi

02/25/2024, 1:29 PM
For me #2 source is good and more cleaner then source #1.
1
j

Joffrey

02/25/2024, 1:51 PM
I wouldn't pay so much attention to the compiled code in general unless you want to investigate particular issues that you or your users experienced. Here I would just look at the source. The second snippet is better in terms of readability. The property name
asBar
might need to be revisited based on the real domain names, as this is usually a function name.
👆 3
e

ephemient

02/25/2024, 3:06 PM
"zero-sized" doesn't have an equivalent in JVM
2
here, enum entries are objects and all constructed when the class is loaded, no matter which way you write it