Kotlin 中的常量——创建它们的推荐方法是什么? [英] Constants in Kotlin -- what's a recommended way to create them?

查看:18
本文介绍了Kotlin 中的常量——创建它们的推荐方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

建议如何在 Kotlin 中创建常量?命名约定是什么?我在文档中没有找到.

How is it recommended to create constants in Kotlin? And what's the naming convention? I've not found that in the documentation.

companion object {
    //1
    val MY_CONST = "something"

    //2
    const val MY_CONST = "something"

    //3
    val myConst = "something"
}

还是……?

推荐答案

避免使用伴随对象.在后台,为可访问的字段创建了 getter 和 setter 实例方法.调用实例方法在技术上比调用静态方法更昂贵.

Avoid using companion objects. Behind the hood, getter and setter instance methods are created for the fields to be accessible. Calling instance methods is technically more expensive than calling static methods.

public class DbConstants {
    companion object {
        val TABLE_USER_ATTRIBUTE_EMPID = "_id"
        val TABLE_USER_ATTRIBUTE_DATA = "data"
    }

改为在object中定义常量.

推荐做法:

object DbConstants {
        const val TABLE_USER_ATTRIBUTE_EMPID = "_id"
        const val TABLE_USER_ATTRIBUTE_DATA = "data"
}

并像这样全局访问它们:DbConstants.TABLE_USER_ATTRIBUTE_EMPID

and access them globally like this: DbConstants.TABLE_USER_ATTRIBUTE_EMPID

这篇关于Kotlin 中的常量——创建它们的推荐方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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