很多人简单的Kotlin的object简单理解为静态。
一般情况下是没有问题的,
但是更准确的理解是object修饰的类是Singleton(单例)。
在类的内部object 前加上 companion, 可以做成属于这个类的Singleton。
class Hoge {
object A {
val fizz = "fizz"
fun foo() { ... }
}
companion object {
val buzz = "buzz"
fun bar() { ... }
}
}
调用方式
fun main() {
// 通常的object
Hoge.A.fizz
Hoge.A.foo()
// companion object
Hoge.buzz
Hoge.bar()
}
个人认为在类内部object和 companion object 功能上没什么区别。有认识不到位的地方请指正。
companion object反编译成java是这样子的
// @Metadataなどは省略しています。
public final class Hoge {
@NotNull
// privateなので、Companionインスタンスのgetterを介してアクセス可能。
private static final String buzz = "buzz";
public static final Hoge.Companion Companion = new Hoge.Companion((DefaultConstructorMarker)null);
public static final class Companion {
// Companionクラス内に宣言されるので、Companionインスタンスを介してアクセス可能。
public final void bar() {
...
}
@NotNull
public final String getBuzz() {
return Hoge.buzz;
}
private Companion() {
}
// $FF: synthetic method
public Companion(DefaultConstructorMarker $constructor_marker) {
this();
}
}
}
在Java里这么调用
public class Main {
public static void main(String[] args) {
Hoge.A.getFizz()
Hoge.A.foo()
Hoge.Companion.getBuzz()
Hoge.Companion.bar()
}
}
为什么Kotlin里没有static静态关键子呢。
“Static constants” in Kotlin 这里提到
Kotlin is designed so that there’s no such thing as a “static member” in a class.
If you have a function in a class, it can only be called on instances of this class.
If you need something that is not attached to an instance of any class, you define it in a package, outside any class (we call it package-level functions):But sometimes you need static constants in your class: for example, to comply with requirements of some framework or to use serialization.
How do you do this in Kotlin? There are two things in Kotlin that resemble Java’s statics: aforementioned package-level functions and class objects.
就是说
・java的static变量(final修饰的字段),在Kotlin里在package级别定义,或者用class object(companion object)就可以
・java的静态方法,在Kotlin里package级别定义就可以
所以说Kotlin不需要static
这么说companion object也是替代static变量用的。
参考
https://qiita.com/tkhs0604/items/261e94a42b7097dfd204