Abdul Mateen
Abdul Mateen

Reputation: 1684

Kotlin - how to know if a String is present in a Constant object?

I'm working on an Android application where I've created an object in Constants file to store some Status values. In one of my classes, I've got a variable of type Status. I need to set the value of status from some data I get from backend. However, the data is in String form. Is there any way I can check whether the data string is in the Status object and potentially cast this string to Status?

NOTE: There can be many custom types like Status, so I want to avoid enums as much as possible given their performance impacts.

Consider the following scenario

// Constants.kt
object Constants {
    ...
    object Status {
        const val OKAY = "okay"
        const val DONE = "done"
        const val PENDING = "pending"
    }
    ...
}


// SomeClass.kt
class SomeClass {
    private var status: Status? = null

    setStatus(status: Status) {
        this.status = status
    }
}

// SomeOtherClass.kt
fun updateStatus() {
    val someClass = SomeClass()
    val status: String = getSomeStringFromServer()
    // add some check to confirm whether status is actually one of Constants.Status
    someClass.setStatus(status) // It wouldn't work because type String and Status are incompatible
}

Upvotes: 0

Views: 612

Answers (1)

Mark
Mark

Reputation: 9929

If this is only a number of finite reasoned states then you can easily use a enum :

enum class Status(val value : String) {
    OKAY("okay"),
    DONE("done"),
    PENDING("pending")
}

Then in order to convert the server string into a Status :

val valueFromServer = "okay"
val status : Status? = enumValues<Status>().firstOrNull { it.value == valueFromServer }

This works for known types and you can easily handle unknown types when the Status is null.

Also for convenience use you can create an extension function :

 private fun String.toStatus() : Status? = enumValues<Status>().firstOrNull { it.value == this }

Usage :

"okay".toStatus()

Upvotes: 1

Related Questions