Mike
Mike

Reputation: 359

How can i constrain a variable to specific allowable values?

In Groovy, is there some equivalent to string literal types in Typescript:

type Choices = 'choice 1' | 'choice 2'
Choices input

Or am I out of luck?

Upvotes: 2

Views: 72

Answers (2)

Szymon Stepniak
Szymon Stepniak

Reputation: 42272

There is no exact equivalent of TypeScript's string literal types (at least not in the same terms as defined here). However, with some small amount of code you can make enums to do something pretty similar to them (not exact behavior, but it might actually work for you).

Consider the following example:

enum Choices {
    CHOICE_1("choice 1"),
    CHOICE_2("choice 2")

    String literal

    private Choices(String literal) {
        this.literal = literal
    }

    static Choices of(String literal) {
        Choices choices = values().find { it.literal == literal }
        if (choices == null) {
            throw new IllegalArgumentException("Choices with literal ${literal} is not supported!")
        }
        return choices
    }
}

Choices input = Choices.of("choice 2")

println input.literal // prints "choice 2"
println input // prints "CHOICE_2"

Choices choice = "CHOICE_1" // coerces String to enums name (but not literal!)

println choice.literal // prints "choice 1"
println choice // prints "CHOICE_1"

Choices.of("asdasd") // throws IllegalArgumentException

Upvotes: 1

dbrin
dbrin

Reputation: 15673

Yes, they are called Enums.

enum MyColors{
  BLUE, RED, WHITE
}

println MyColors.values()

http://grails.asia/groovy-enum-examples

Upvotes: 0

Related Questions