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

  1. object DefaultValues {
        val FILES_TO_DOWNLOAD = 100
    }
    

    class DefaultValues {
        companion object {
            val FILES_TO_DOWNLOAD = 100
        }
    }
    
  2. 没有类或对象包装器:

    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

推荐答案

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

With Kotlin 1.0.2 the compiled bytecode shows that

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

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

    还有一个getter,在引用属性时称为:

     // 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().

  2. 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字段:

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

    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).


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

Kotlin相关问答推荐

数据源配置

如何将消费者放入 Kotlin 的 map 中?

如何避免键盘打开时jetpack compose 内容上升

在jetpack compose中将默认方向设置为横向?

如何使用成员引用在 Kotlin 中创建属性的分层路径

compareBy 如何使用布尔表达式在 kotlin 中工作

未为任务启用 Gradle 构建缓存

从列表中的每个对象中 Select 属性

在 Spring Framework 5.1 中注册具有相同名称的测试 bean

带有迭代器函数的 Kotlin 无限序列

作为 Kotlin 中的函数的结果,如何从 Firestore 数据库返回列表?

防止导航到同一个片段

如何在Spring Boot应用程序上启用承载身份验证?

requireNotNull vs sure !! 操作符

Kotlin内联扩展属性

如何将 Kotlin 日期中的字符串或时间戳格式化为指定的首选格式?

Kotlin val difference getter override vs assignment

如何在协程之外获取 Flow 的值?

应用程序在使用 Google Play 服务时遇到问题

WebFlux 功能:如何检测空 Flux 并返回 404?