Java Kotlin 中的私有构造函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46847734/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 02:29:41  来源:igfitidea点击:

Private constructor in Kotlin

javaconstructorkotlinvisibility

提问by Marvin

In Java it's possible to hide a class' main constructor by making it privateand then accessing it via a publicstaticmethod inside that class:

在 Java 中,可以通过创建类的主构造函数private然后通过publicstatic该类中的方法访问它来隐藏类的主构造函数:

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;
    }

    // ...
}

How can the same be reached with Kotlin without separating the class into a publicinterface and a privateimplementation? Making a constructor privateleads to it not being accessible from outside the class, not even from the same file.

在不将类分为public接口和private实现的情况下,如何使用 Kotlin实现相同的功能?创建一个构造函数private会导致它不能从类外部访问,甚至不能从同一个文件访问。

采纳答案by rafal

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

回答by Marvin

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())

可以访问伴随对象中的方法,就像它们是周围类的成员一样(例如Foo.constructorA()

回答by Abhinandan Chada

This is the Answer

class Hide private constructor(val someData: Data) {

}

By declaring the constructor private, we can hiding constructor.

回答by Omar

I've been coding in Java for a few years, and learning now Kotlin as a new language. From what I found while trying to make a Singleton without being able to call the constructor was to make a primary constructor in the class as private declared, and then calling your function (in my case the singleton) from a companion object like this.

我已经用 Java 编码几年了,现在正在学习 Kotlin 作为一种新语言。从我在尝试创建一个不能调用构造函数的单例时发现的是,在类中创建一个主构造函数作为私有声明,然后从这样的伴随对象调用你的函数(在我的情况下是单例)。

open class Singleton private constructor() {

fun produceSomeChicken(): String {
    return "CHICKEN"
}

companion object {
    private var INSTANCE : Singleton? = null
    fun getInstance(): Singleton {
        if (INSTANCE == null) {
            println("IS NULL")
            INSTANCE = Singleton()
            println("INSTANCE CREATED")
        }
        return INSTANCE as Singleton
    }

}}

and then calling the function from anywhere you want like that for example

然后从任何你想要的地方调用该函数,例如

println(Singleton.getInstance().produceSomeChicken()) //instance created without calling constructor
//println(Singleton().produceSomeChicken()) //is not possible to call, prevented by using private constructor (gives back compile error)

Eventhough the question is old, I still hope it helps some of you! You're welcome

尽管这个问题很老,但我仍然希望它对你们中的一些人有所帮助!别客气