[WIP]Kotlin里面如何定义定数

There's no static keyword in Kotlin. If you want static access to certain fields or methods of your class, you should put them under a companion object.

Even though there's no static keyword in Kotlin, it's easy to define constants that are globally accessible. It's also quite easy to get this wrong and introduce redundant methods and object allocations into the bytecode. The decompiler tool can help you locate and fix this kind of issues, and comes with an additional benefit - you'll quickly learn how all that Kotlin magic works under the hood!

class MyFragment {
    private val MY_KEY = "my_key"
}

→  is an instance field.
private const val MY_KEY = "my_key" 
class MyFragment {
}

→  is a top-level "static" member
This is why you have a MyFragmentKt class generated: top-level members are compiled into a class of the name [Filename]Kt.

private top-level declarations have different semantics and do not become members of the package, as they aren't accessible outside the file where they are declared. This also means that private top-level declarations are naturally coupled to that file.

** Kotlin思维
class MyFragment {
    companion object {
        private const val MY_KEY = "my_key"
    }
}

→  This way, MY_KEY is (from Java) a static member of the MyFragment class, since JvmStatic is inferred for const variables. There will be a Companion class generated (but it will be empty).

** Java思维。

Links

Where Should I Keep My Constants in Kotlin?

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,151评论 0 10
  • 前段时间公司项目中需要用到图片识别算法,需要在iOS中调用Lua方法。 but,从来没有接触过lua肿么办,只知道...
    快到碗里来____阅读 8,089评论 0 4
  • 小兴说:老师您最大的不同就是课堂上欢迎错误,正是如此,让我们有了更大勇气去展示自己!我微笑回答:正是你们的...
    源味清风阅读 2,472评论 0 0
  • 前几天和朋友去看了北京遇上西雅图之不二情书,与其说是北西的第二部,倒不如说是一部全新的电影,不变的也只有主演和导演...
    西东74阅读 3,738评论 0 0
  • 距离这个通往广泛世界的开口,还有31天。我有点想放弃了,当班主任为我做分数分析的时候,他说"你的化物怎么感觉没学一...
    BellaMealing阅读 975评论 0 1