Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin sealed classes assigning property constants

Tags:

kotlin

kotlin_version = '1.2.30'

I have a sqlite table that has a Integer value for a column called direction. That will store the Integer property based on the enum constant.

i.e will insert 40 into the table:

saveDirection(Direction.Right.code)

I have a enum class written in kotlin with property constants assigned.

 enum class Direction(val code: Int) {
        UP(10),
        DOWN(20),
        LEFT(30),
        RIGHT(40),
        NONE(0)
    }

I am wondering if I can do the same with sealed classes

sealed class Direction {
    abstract val code: Int

    data class Up(override val code: Int): Direction()
    data class Down(override val code: Int): Direction()
    data class Left(override val code: Int): Direction()
    data class Right(override val code: Int): Direction()
    data class None(override val code: Int): Direction()
}

However, this won't work as the saveDirection(direction: Int) is expecting an Int value:

saveDirection(Direction.Right(40))

Is this possible to assign constant properties to sealed classes so that you can get the constant property like in enums?

Thanks for any suggestions,

like image 967
ant2009 Avatar asked Sep 19 '25 13:09

ant2009


1 Answers

You could use sealed classes like this:

sealed class Direction(val code: Int) { 
    override fun equals(other: Any?): Boolean = other is Direction && code == other.code
    override fun hashCode(): Int = code
}

class Up : Direction(10)
class Down : Direction(20)
class Left : Direction(30)
class Right : Direction(40)
class None : Direction(0)

However, given the limited context of the question, it is unclear what exactly you would gain by this. In fact, in this simple case, Kotlin does not allow your subclasses to be marked as data class:

Data class must have at least one primary constructor parameter

The solution provided above does not have any advantage over enums, in fact it is more verbose and error-prone than an enum-based definition, so why not just use those?

like image 77
blubb Avatar answered Sep 23 '25 12:09

blubb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!