是否有可能限制开关使用kotlin / JAVA中的特定情况?
是否可以限制使用特定情况下的开关。
这是我的情况:
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; } } }
所以在这里我定义了一个StringDef接口,并限制style()
只是返回@NotificationStyle
指定的值,这里是我的开关情况
// 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 }
我知道obj.style()
将只返回限制值,但我想以某种方式限制开关的情况下甚至在这里提供这种情况
case "Not available to execute": //Something something break;
因为这将永远是无法访问的代码。
*请不要查找代码和语法,只是在这里寻找概念。
谢谢。
你正在切换一个String
,对吗? 这就是为什么你可以添加案例,这不会真的发生(如"Not available to execute"
)。 你为什么不把你的可能的字符串改成一个enum
并让obj.style
从这个枚举返回一个常量? 这就是你如何能够使这些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") } }