在 kotlin 中有必要用常量注解吗?

2020-07-15 09:59:37 +08:00
 w950888

在 kotlin 中有必要用常量注解吗?如果需要用下面的常量类用 kotlin 应该怎么写呢,直接转换 kotlin 会报错。

import androidx.annotation.StringDef;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author Luke
 * @version 1.0.0
 * @time 2020/7/13 2:14 PM
 * @description 常量池
 */
public class Constant {

    @IntDef({
            AlertCode.SYSTEM,
    })
    @Documented
    @Retention(RetentionPolicy.SOURCE)
    @Target({ElementType.PARAMETER, ElementType.FIELD, ElementType.METHOD})
    public @interface AlertCode {
        int SYSTEM = 0;
    }

}
5837 次点击
所在节点    Android
10 条回复
gz911122
2020-07-15 10:11:00 +08:00
这是干啥用的啊?
w950888
2020-07-15 10:16:11 +08:00
@gz911122 常量池,同时具有类似枚举限定范围的作用,要比枚举性能好
gz911122
2020-07-15 10:21:15 +08:00
@w950888 哦我想起来了 加在参数上, 限制输入的...

android 专用, 后端没有...
lianyue13
2020-07-15 10:26:11 +08:00
```kotlin
class Constant {
@IntDef(AlertCode.SYSTEM)
@Documented
@Retention(AnnotationRetention.SOURCE)
@Target(AnnotationTarget.LOCAL_VARIABLE, AnnotationTarget.FIELD, AnnotationTarget.FUNCTION)
annotation class AlertCode {
companion object {
const val SYSTEM = 0
}
}
}
```
sagaxu
2020-07-15 10:28:36 +08:00
@w950888 jake wharton 说 enum 和 int 性能一样
loshine1992
2020-07-15 10:32:15 +08:00
ART 之后直接用枚举就可以了
w950888
2020-07-15 10:32:17 +08:00
@lianyue13 非常感谢
w950888
2020-07-15 10:35:22 +08:00
@sagaxu 在 Android 里 @IntDef 比枚举更省内存
sagaxu
2020-07-15 10:54:58 +08:00
@w950888 省 dex 字节码,但不省内存。ART 会自动优化,运行时 enum 和 int 没区别。
w950888
2020-07-15 11:08:59 +08:00
@sagaxu (* ̄︶ ̄) 懂了,谢谢哈

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/690132

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX