V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
w950888
V2EX  ›  Android

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

  •  
  •   w950888 · 2020-07-15 09:59:37 +08:00 · 5234 次点击
    这是一个创建于 1353 天前的主题,其中的信息可能已经有所发展或是发生改变。

    在 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;
        }
    
    }
    
    10 条回复    2020-07-15 11:08:59 +08:00
    gz911122
        1
    gz911122  
       2020-07-15 10:11:00 +08:00
    这是干啥用的啊?
    w950888
        2
    w950888  
    OP
       2020-07-15 10:16:11 +08:00
    @gz911122 常量池,同时具有类似枚举限定范围的作用,要比枚举性能好
    gz911122
        3
    gz911122  
       2020-07-15 10:21:15 +08:00
    @w950888 哦我想起来了 加在参数上, 限制输入的...

    android 专用, 后端没有...
    lianyue13
        4
    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
        5
    sagaxu  
       2020-07-15 10:28:36 +08:00 via Android
    @w950888 jake wharton 说 enum 和 int 性能一样
    loshine1992
        6
    loshine1992  
       2020-07-15 10:32:15 +08:00
    ART 之后直接用枚举就可以了
    w950888
        7
    w950888  
    OP
       2020-07-15 10:32:17 +08:00
    @lianyue13 非常感谢
    w950888
        8
    w950888  
    OP
       2020-07-15 10:35:22 +08:00
    @sagaxu 在 Android 里 @IntDef 比枚举更省内存
    sagaxu
        9
    sagaxu  
       2020-07-15 10:54:58 +08:00 via Android
    @w950888 省 dex 字节码,但不省内存。ART 会自动优化,运行时 enum 和 int 没区别。
    w950888
        10
    w950888  
    OP
       2020-07-15 11:08:59 +08:00
    @sagaxu (* ̄︶ ̄) 懂了,谢谢哈
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2498 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 15:44 · PVG 23:44 · LAX 08:44 · JFK 11:44
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.