utils函数和常量应该定义在哪里,顶级或对象(单个实例)?

时间:2018-02-24 08:51:15

标签: java kotlin

对于utils函数和常量,顶级或对象(单实例)是否有最佳实践/约定?

如果使用顶级,例如,文件utils.kt,我们不能为utils.kt写注释,调用者可能不知道什么关系,属于那些函数和常量。

如果使用对象(单个实例),那么任何kotlin代码都会喜欢:

Xxx.xxx

什么是最好的?

1 个答案:

答案 0 :(得分:0)

不确定这是否有帮助。但你可以在util类中使用伴随对象来访问它们,就好像它们是静态方法一样。看看这个例子on how to use companion object to achieve static method like behavior in kotlin

class ClassWithCompanionObject {

constructor() {
    numberOfInstancesOfClass++
    println("create instance number $numberOfInstancesOfClass of ClassWithCompanionObject")
}

/**
 * companion Object is a singleton object
 * so only one instance of it is created..
 * similar to Java Static block .. Kotlin doesn't
 * have static. so everything inside a companion
 * object can be thought of as static and will be
 * initialized only once. or you can think of it
 * as class level instead on instance level.
 */
companion object {

    private var numberOfInstancesOfClass = 0

    fun printNumberOfInstancesOfClassValue(){
        println("numberOfInstancesOfClass = $numberOfInstancesOfClass !")
    }
 }

}


fun main(args: Array<String>) {

ClassWithCompanionObject()
ClassWithCompanionObject()
ClassWithCompanionObject()
ClassWithCompanionObject.printNumberOfInstancesOfClassValue()

}