我有一个注释需要defaultValue
为编译时常数。我拿defaultValue
from enum
below:
enum class RaceType {
MARATHON,
SPRINT;
companion object {
fun apply(type: RaceType): RaceDto {
return when (type) {
MARATHON -> MarathonDto()
SPRINT -> SprintDto()
}
}
}
}
My dto
如下:
interface RaceDto {
}
data class MarathonDto: RaceDto
data class SprintDto: RaceDto
当我使用注释时@QraphQLArgument(defaultValue = RaceType.SPRINT.name)
Kotlin 需要RaceType.SPRINT.name
为编译时常数。
注解实现本身:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER})
public @interface GraphQLArgument {
String NONE = "\n\t\t\n\t\t\n\ue000\ue001\ue002\n\t\t\t\t\n";
String NULL = "\n\t\t\n\t\t\n\ue000\ue001\ue002\ue003\n\t\t\t\t\n";
String name();
String description() default "";
String defaultValue() default "\n\t\t\n\t\t\n\ue000\ue001\ue002\n\t\t\t\t\n";
Class<? extends DefaultValueProvider> defaultValueProvider() default JsonDefaultValueProvider.class;
}
我翻阅了类似的问题 https://stackoverflow.com/questions/44038721/constants-in-kotlin-whats-a-recommended-way-to-create-them但没有看到如何解决它的方法。我还发现article https://blog.egorand.me/where-do-i-put-my-constants-in-kotlin/与主题相关,但到目前为止没有任何效果。
旁注:我无法更改注释,因为它来自库,而且我也无法更改库。
总而言之,有没有一种方法可以使enum
Kotlin 中的编译时常量要在注释中使用吗?
有没有办法让enum
Kotlin 中的编译时常量要在注释中使用吗?
不,因为正式enum
s 不是 Java 中的编译时常量 https://stackoverflow.com/a/28296706/185498.
但是请考虑sealed
课程:
sealed class RaceType {
object MARATHON: RaceType() {
const val name = "MARATHON" // copy-paste is required here until https://youtrack.jetbrains.com/issue/KT-16304
}
object SPRINT: RaceType()
companion object {
fun apply(type: RaceType): RaceDto {
return when (type) { // the check is in compile time, because of sealed class
MARATHON -> MarathonDto()
SPRINT -> SprintDto()
}
}
}
}
仍然需要一小部分复制粘贴。请投票kotlin 编译器错误 https://youtrack.jetbrains.com/issue/KT-16304 or 关注此主题 https://discuss.kotlinlang.org/t/class-property-name-should-be-compile-time-constant/9331/2?u=imanushin.
但是,据我了解,这并不能解决您的问题@QraphQLArgument(defaultValue = RaceType.SPRINT.name)
不幸的是,因为类的名称与值不同。换句话说,对于密封类,您需要编写代码将输入字符串转换为它们。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)