gpt4 book ai didi

java - 是否可以限制切换仅在 kotlin/JAVA 中使用特定情况?

转载 作者:行者123 更新时间:2023-12-02 12:02:06 25 4
gpt4 key购买 nike

是否可以限制使用特定情况的开关。

这是我的场景:

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 接口(interface)并限制 style() 只是返回 @NotificationStyle 指定的值,这是我的 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
}

我知道 obj.style() 只会返回受限值,但我想以某种方式限制 switch case 甚至在此处提供这种情况

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

因为这始终是无法访问的代码。

*请不要寻找代码和语法,只在这里寻找概念。

谢谢。

最佳答案

您正在对String进行切换,对吧?这就是为什么您当然可以添加案例,但这不会真正发生(例如“无法执行”)。为什么不将可能的字符串更改为 enum 并让 obj.style 从该枚举返回一个常量?这就是限制这些字符串的方法。

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")
}
}

关于java - 是否可以限制切换仅在 kotlin/JAVA 中使用特定情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47173199/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com