简体   繁体   中英

Is it possible to restrict switch to use particular cases only in kotlin/JAVA?

Is it possible to restrict switch for using particular case.

Here is my scenario :

class XYZ {
    public static final String DEFAULT = "DEFAULT";
    public static final String BIG_TEXT = "BIG_TEXT";
    public static final String BIG_PICTURE = "BIG_PICTURE";
    public static final String CAROUSEL = "CAROUSEL";
    public static final String GIF = "GIF";

     @Retention(RetentionPolicy.SOURCE)
    @StringDef({DEFAULT, BIG_TEXT, BIG_PICTURE, CAROUSEL, GIF})
    public @interface NotificationStyle {}

    @NotificationStyle
    public String style() {
        if (CollectionUtils.isNotEmpty(carouselItems)) {
            return CAROUSEL;
        } 
        if (CollectionUtils.isNotEmpty(gifItems)) {
            return GIF;
        } else {
            return DEFAULT;
        }
    }
}

So here I have define one StringDef interface and restricting style() just to return @NotificationStyle specified values and here is my switch case

// Some other class

XYZ obj = new XYZ()

switch (obj.style()) {
    case XYZ.BIG_PICTURE:
    //Something something
    break;
    case XYZ.BIG_PICTURE:
    //Something something
    break;
    case "Not available to execute":
    //Something something
    break;
    default : //Something something
}

I know obj.style() will only return restricted values but I want to somehow restrict switch case to even provide this case here

case "Not available to execute":
    //Something something
    break;

As this will be unreachable code always.

*Please do not look for the code and syntax , just looking for concept here.

Thanks.

You're doing a switch over a String , right? That's why you can, of course, add cases, that won't really happen (like "Not available to execute" ). Why don't you just change your possible Strings to an enum and make obj.style return a constant from that enum? This is how you can restict those Strings .

fun style(): XYZValues {
    if (true) {
        return XYZValues.BIG_TEXT
    }
    return XYZValues.DEFAULT
}

enum class XYZValues(desc: String) {
    DEFAULT("DEFAULT"),
    BIG_TEXT("BIG_TEXT")
    //more }

}

fun main(args: Array<String>) {
    when (style()) {
        XYZValues.BIG_TEXT -> println("1")
        XYZValues.DEFAULT -> println("2")
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM