How to expose an enum in a plugin

I have a script plugin with a nested enum:

class MyPlugin implements Plugin<Project>  {

    Day day;

    Day day() {
        return day;
    }

    enum Day {
        SUNDAY, MONDAY; //...
    }

    void apply(Project project) {
        project.getExtensions().create("myplugin", MyPlugin.class);
//        project.myplugin.getExtensions().create("day", Day.class);
    }
}

In the build script, I want to have a switch:

switch (myplugin.day()) {
    case SUNDAY:
    case MONDAY:
    default:
}

This gives the error:
Could not get unknown property 'SUNDAY' for root project...

So I tried to add it as an extension and uncomment the line in the plugin, then I tried:

switch (myplugin.day()) {
    case myplugin.Day.SUNDAY:
    case myplugin.Day.MONDAY:
    default:
}

But uncommenting the line gives the error:
Class MyPlugin.Day is not a class or interface

So how can I switch over the enum values?

Your extension is called day, not Day, so in the second variant it would probably be myplugin.day.SUNDAY.

Alternatively, for the first variant, you probably simply missed to add the necessary import static MyPlugin.Day.SUNDAY etc. statements.

Besides that imperative logic like a switch in a build script is bad practice of course. :slight_smile:


Also, I recommend you switch to Kotlin DSL. By now it is the default DSL, you immediately get type-safe build scripts, actually helpful error messages if you mess up the syntax, and amazingly better IDE support if you use a good IDE like IntelliJ IDEA or Android Studio.

Thanks. I’m trying to bring a very old big Gradle build into modernity, so it takes some compromises.

There’s code there that sets variables based on which OS and architecture the build is running on, and also checks if the OS-arch combination is supported at all. That’s what I’m simplifying. What’s the proper way of handling this?

Hard to answer generically.
You sure can do conditional code in build scripts, it is just most often better to instead put imperative logic into convention plugins or custom tasks or similar and then use those from the build scripts.