Android我爱编程

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

2018-06-15  本文已影响13人  假装在去天使之城的路上

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?

上一篇下一篇

猜你喜欢

热点阅读