Kotlin 的私人建筑商

在 Java 中,可以通过将类的主构造函数设置为 private,然后通过类中的 public static方法访问它来隐藏类的主构造函数:

public final class Foo {
/* Public static method */
public static final Foo constructorA() {
// do stuff


return new Foo(someData);
}


private final Data someData;


/* Main constructor */
private Foo(final Data someData) {
Objects.requireNonNull(someData);


this.someData = someData;
}


// ...
}

如果不将类分离成一个 public接口和一个 private实现,Kotlin 如何能够实现同样的功能?创建构造函数 private会导致不能从类外部访问它,甚至不能从同一个文件访问它。

55777 次浏览

This is possible using a companion object:

class Foo private constructor(val someData: Data) {
companion object {
fun constructorA(): Foo {
// do stuff


return Foo(someData)
}
}


// ...
}

Methods inside the companion object can be reached just like if they were members of the surrounding class (e.g. Foo.constructorA())

You can even do something more similar to "emulating" usage of public constructor while having private constructor.

class Foo private constructor(val someData: Data) {
companion object {
operator fun invoke(): Foo {
// do stuff


return Foo(someData)
}
}
}


//usage
Foo() //even though it looks like constructor, it is a function call
This is the Answer


class Hide private constructor(val someData: Data) {


}


By declaring the constructor private, we can hiding constructor.