darth jemico
darth jemico

Reputation: 737

How can i limit use of enum values in Kotlin?

Can I somehow limit the usage of incoming enum with kotlin language features? I have an enum, for example

enum class Message {
    NORMAL,
    URGENT,
    LETHAL
}

When i get an incoming dto, i need to assure that it contains only URGENT or LETHAL enum values. I'm a bit lazy to write a validator, so could anyone advice some kotlin magick for that case?

Upvotes: 0

Views: 509

Answers (1)

Neo
Neo

Reputation: 2039

Simple require assertion:

val message = Message.NORMAL
require(message in listOf(URGENT, LETHAL)) { "Message must be either urgent or lethal" }

Upvotes: 1

Related Questions