Yurowitz
Yurowitz

Reputation: 1396

How to make a function use only predefined constants in its constructor parameters in Kotlin?

I've been looking around trying to figure this out. But even reading the source code of some libraries didn't give me a good understanding of how to do this:

I have a function in Kotlin :

fun setCustomMode(customMode: Int) {
}

And I have a few Int constants: CUSTOM_MODE_1, CUSTOM_MODE_2

How can I allow the function setCustomMode to only accept the constants above. I searched a lot but I can't even seem to know how to ask the question properly on Google. Please help me.

Upvotes: 0

Views: 149

Answers (1)

Ferhatwi
Ferhatwi

Reputation: 111

You can achive this by declaring enum class. Sample is below:

enum class Modes(val id: Int) {
    CUSTOM_MODE_1(123), //Desired int
    CUSTOM_MODE_2(456) //Another desired int
    //...
}

fun setCustomMode(modes: Modes) {
    println("Name of the mode is " + modes.name)
    println("ID of the mode is " + modes.id)
}

fun main() {
    setCustomMode(Modes.CUSTOM_MODE_1) //Anything from Modes class
}

Upvotes: 1

Related Questions