Kotlin中的静态数据 [英] Static data in Kotlin

查看:59
本文介绍了Kotlin中的静态数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请告诉我,这个示例在Java方面有什么区别

Please tell me, is there any difference (in terms of Java) in this examples:

object DefaultValues {
    val FILES_TO_DOWNLOAD = 100
}

class DefaultValues {
    companion object {
        val FILES_TO_DOWNLOAD = 100
    }
}

  • 没有类或对象包装器:

  • Without class or object wrapper:

    const val DEFAULT_FILES_TO_DOWNLOAD = 100
    

    val DEFAULT_FILES_TO_DOWNLOAD = 100
    


  • 真正的定义方式是什么?:


    What is the true way to define?:

    public static final int FILES_TO_DOWNLOAD = 100
    

    推荐答案

    您可以使用 Kotlin字节码查看器找出这些选项被编译成什么.

    You can use Kotlin bytecode viewer to find out what these options are compiled to.

    使用Kotlin 1.0.2时,编译后的字节码显示

    With Kotlin 1.0.2 the compiled bytecode shows that

      objectcompanion object中的
    1. val属性被编译为类内的private static final字段:

    1. val property in object or companion object is compiled into a private static final field inside the class:

     // access flags 0x1A
     private final static I FILES_TO_DOWNLOAD = 100
    

    和一个吸气剂,当引用该属性时会被调用:

    and a getter, which is called when referring to the property:

     // access flags 0x1019
     public final static synthetic access$getFILES_TO_DOWNLOAD$cp()I
    

    在Java中,getter可以分别称为DefaultValues.INSTANCE.getFILES_TO_DOWNLOAD()DefaultValues.Companion.getFILES_TO_DOWNLOAD().

    From Java, the getter can be called as DefaultValues.INSTANCE.getFILES_TO_DOWNLOAD() or DefaultValues.Companion.getFILES_TO_DOWNLOAD() respectively.

    Non- const顶级属性被编译为与(1)相同,唯一的区别是现在字段和getter放置在FilenameKt类中.

    Non-const top level property is compiled to the same to (1) with only difference that the field and getter are placed inside FilenameKt class now.

    但是顶层const val会被编译为public static final字段:

    But top level const val is compiled into a public static final field:

    // access flags 0x19
    public final static I DEFAULT_FILES_TO_DOWNLOAD = 100
    

    在对象内部声明const val时,将产生相同的公共static final字段.另外,如果添加> @JvmField 注释(1)中声明的属性.

    The same public static final field will be produced when a const val is declared inside an object. Also, you can achieve the same resulting bytecode if you add @JvmField annotation to the properties declared in (1).


    最后,您可以在object或顶层使用const@JvmField定义public static final字段.


    Concluding that, you can define public static final field using const or @JvmField either in an object or at top level.

    这篇关于Kotlin中的静态数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆