在Kotlin中,是否可以使用工厂函数创建具有私有构造函数的类的实例?

My goal is to enforce the factory function to be used and to prevent instantiation via the class's constructor.

例子:

// factory function, valid
val myInstance = myClassOf()

// class instantiation, invalid
val myInstance = MyClass()

我正在try 模仿一些内置工厂函数的行为,比如intArrayOf().

// works
val myIntArray = intArrayOf()

// not possible as IntArray has a private constructor
val myIntArray = IntArray()

推荐答案

你可以这样做:

import MyClass.Companion.myClassOf

class MyClass private constructor() {
    companion object {
        fun myClassOf() = MyClass()
    }
}

//val myInstance1 = MyClass() // not allowed
val myInstance2 = myClassOf()

Kotlin相关问答推荐

如何将时间值格式化为00:00和00:00:00 Kotlin?""""

如何确保Kotlin子类已完成初始化?

&x是T&q;和&q;(x为?T)!=空(&Q;)?

如何在Spring Boot中注册新的集合工厂

有什么方法可以要求在 kotlin 中的类型参数上进行注释?

验证构造函数中的值组合

通过顺序多米诺骨牌操作列表管理对象的最佳方法是什么?

使用 Discord4j 交叉发布 Discord 消息

如何从kotlin中的ArrayList中删除所有元素

如何使用 Hilt 注入应用程序:ViewModel 中的上下文?

如何为你的 Flutter 元素添加 Kotlin 支持?

Kotlin 语言是如何用 Kotlin 编写的?

如何在 kotlin 的片段类中更改 ActionBar 标题?

runOnUiThread 没有调用

防止导航到同一个片段

Kotlin 具体化的泛型不会按计划保持类型

Android:在 DAO 中使用 Room 数据库和 LiveData 架构

将多个 Kotlin 流合并到一个列表中,而无需等待第一个值

如何在kotlin用mockito模仿lambda

在 Kotlin 中声明 Byte 会出现编译时错误The integer literal does not conform to the expected type Byte