Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Enum initializers from rawValue #94

Closed
angelolloqui opened this issue Feb 18, 2019 · 6 comments
Closed

Add Enum initializers from rawValue #94

angelolloqui opened this issue Feb 18, 2019 · 6 comments

Comments

@angelolloqui
Copy link
Owner

In Swift, when you have an enum like:

public enum PaymentMethodType: String {
    case direct = "DIRECT",  creditCard = "CREDIT_CARD"
}

The you can instantiate the enum from a rawValue like:
let type = PaymentMethodType(rawValue: "DIRECT")

In Kotlin, the equivalent would be:

enum class PaymentMethodType constructor(var rawValue: String) {
    direct("DIRECT"),  creditCard("CREDIT_CARD");
}

But that does not provide the Swift constructor from rawValue.

An option, would be to create an additional method on the Kotlin code like:

enum class PaymentMethodType constructor(var rawValue: String) {
    direct("DIRECT"),  creditCard("CREDIT_CARD");

    companion object {
        fun from(rawValue: String): PaymentMethodType? =
                values().firstOrNull { it.rawValue == rawValue }
    }
}

But this also affects the way the caller needs to invoke the instantiation to:

val type = PaymentMethodType.from(rawValue = "DIRECT")

@angelolloqui
Copy link
Owner Author

For reference, there is also a EnumClass.valueOf(value: String): EnumClass method in Kotlin out of the box, but that one throws an exception if the value is not found, while the Swift version returns an optional

@angelolloqui
Copy link
Owner Author

Wait, we should try this approach:

enum class PaymentMethodType constructor(var rawValue: String) {
    direct("DIRECT"),  creditCard("CREDIT_CARD");

    companion object {
         operator fun invoke(rawValue: String) = PaymentMethodType.values().firstOrNull { it.rawValue == rawValue }
    }
}

Because, apparently that works as well, and allows to keep the same caller code:

val method = PaymentMethodType(rawValue = "DIRECT")

@torlangballe
Copy link
Collaborator

torlangballe commented Feb 18, 2019 via email

@torlangballe
Copy link
Collaborator

Do you want me to add this in a new branch, or will you do it?

@angelolloqui
Copy link
Owner Author

I think you already got some stuff working for this, didn't you? if so, please go ahead. Otherwise, I will try to find some time, but as usual, I can not promise on dates.

@angelolloqui
Copy link
Owner Author

Merged with #97

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants