Hi everyone, Is there a way to have a variable or ...
# general-advice
a
Hi everyone, Is there a way to have a variable or class have either the type A or B? I have seen something in Arrow EitherA, B and I wonder if there's something in the language itself too. If that's not possible I have two enum classes that I want to merge the values at some places so either value can be possible.
s
There are no union types, yet 😞. This is the ticket to follow: https://youtrack.jetbrains.com/issue/KT-13108 For your enums, you could use a (possibly sealed) interface:
Copy code
sealed interface AorB
enum class A: AorB { a, b, c }
enum class B: AorB { x, y, z }
a
Wow this was so easy and embarrassing to ask 😄
s
Having enums implement interfaces is a neat feature that's very easy to overlook! I learned about it back in Java, but I didn't know it was possible until I saw it done in another codebase. So don't be embarassed!
❤️ 1
a
The problem I see now is that the sealed interface must be in the same package as where we implement it.
Copy code
package core.definitions.boson

import core.definitions.ParticleType
import core.definitions.attrs.ColorCharge
import core.definitions.attrs.ElectricCharge
import core.definitions.attrs.Spin
import core.utils.idGen

interface Boson : ParticleType {
    val type: BosonType
    val mass: Double
    val electricCharge: ElectricCharge
    val colorCharge: ColorCharge
    val spin: Spin
        get() = Spin.One
    val id: Long
        get() = idGen.incrementAndGet()
}
And The sealed interface is in
Copy code
package core.definitions

sealed interface ParticleType
I'm getting an error from intelliJ to move Boson into the defnitions package directory.
s
Yeah, that's true. You can drop the
sealed
keyword and just use a normal interface, but then you'll lose the ability to have an exhaustive
when
over both enums.
a
Yea. That's seems necessary. Thanks