Hey guys, I have a little argue with my teamlead a...
# codereview
g
Hey guys, I have a little argue with my teamlead about Kotlin code style, please help me in solving it 🙂 We're upgrading Kotlin version from 1.8.10 to 1.8.21 where enum secondary constructors are actually broken (issue is fixed in 1.9.0-Beta, but we can't use it yet). I refactored our only enum which caused compiler crash to have only primary constructor and new code actually seems better to me, but teamlead says the old one was better. Please tell me what do you think about these two versions 🙂 Code in 🧵
1️⃣ 1
2️⃣ 10
Old:
Copy code
enum class MyEnum {
    A("a"),
    B("b"),
    C("c", "123"),
    ;

    val field1: String
    val field2: String

    constructor(field1: String) {
        this.field1 = field1
        this.field2 = "field2 of $name"
    }

    constructor(field1: String, field2: String) {
        this.field1 = field1
        this.field2 = field2
    }
}
New:
Copy code
enum class MyEnum(
    val field1: String,
    customField2: String? = null,
) {
    A("a"),
    B("b"),
    C("c", "123"),
    ;

    val field2 = customField2 ?: "field2 of $name"
}
e
why not
Copy code
enum class MyEnum(
    val field1: String,
    val field2: String = "field2 of $name",
)
1
p
1 is very “Java but with Kotlin syntax’ 2 (and especially ephemient’s 3) are actually idiomatic Kotlin IMO
g
Third option doesn't work because Enum::name is inaccessible at this point, otherwise yeah it would be better
e
ah you're right, the defaults are resolved before the super constructor is invoked
in any case, Kotlin isn't as strict as Swift where only "designated initializers" (primary constructors) can be used by subclasses, but even in Java I'd prefer to have a single primary constructor that any other (secondary) constructor delegates to. and like many other Java best practices, Kotlin makes it easy to do the right thing by default
c
I hate multiple constructors- I always assumed kotlin made them look gross to make people avoid using them 😂. I feel like the second one is far easier to read.