I have static function which is limited to some context eg only for docs. There are 2 alternative ways to define it as top-level function or function in an object.

1.

package com.armsoft.mtrade.data.pref

import com.armsoft.mtrade.App
import com.armsoft.mtrade.domain.model.DocSaveType

object DocPrefManager {
    private const val DOC_PREF = "DOC_PREF"

    private const val KEY_ORDER_SAVE_TYPE = "KEY_ORDER_SAVE_TYPE"

    @JvmStatic
    fun setOrderSaveType(orderSaveType: DocSaveType) {
        val context = App.getContext()
        val sharedPreferences = context.getSharedPreferences(DOC_PREF, 0)
        val editor = sharedPreferences.edit()
        editor.putString(KEY_ORDER_SAVE_TYPE, orderSaveType.getCode())
        editor.commit()
    }
}

2.

package com.armsoft.mtrade.data.pref

import com.armsoft.mtrade.App
import com.armsoft.mtrade.domain.model.DocSaveType

fun setOrderSaveType(orderSaveType: DocSaveType) {
    val context = App.getContext()
    val sharedPreferences = context.getSharedPreferences(DocPrefManager.DOC_PREF, 0)
    val editor = sharedPreferences.edit()
    editor.putString(DocPrefManager.KEY_ORDER_SAVE_TYPE, orderSaveType.getCode())
    editor.commit()
}

The advantage of top-level function that it is not wrapped in an object and disadvantage that it can be accessed from everywhere without class name prefix. Are there advantages or disadvantages or best practice for such cases?

Kotlin相关问答推荐

Kotlin中函数引用的否定

在Kotlin 有更好的结合方式?

访问者闭包中的Kotlin序列yield 率

kotlin短路列表判断吗?

如何在 kotlin 中的数据类中为变量提供多种类型

Kotlin .如何用从 1 到 90 的 5 个唯一数字填充列表中的每一行?

Kotlin 函数有 2 个参数用于对 Map 或 List 进行排序

为什么 Kotlin 中的 Double 和 Long 类型不推荐直接转换为 Char?

如何在 Kotlin 中实现 Composition UML 关系?

Kotlin 可打包类抛出 ClassNotFoundException

Kotlin:泛型、反射以及类型 T 和 T:Any 之间的区别

找不到 androidsdk.modules

如何使 TextInputEditText 只读?

如何使用 Kotlin Coroutines 使 setOnClickListener debounce 1 秒?

为什么 Kotlin Pair 中的条目不可变?

Kotlin:什么是 kotlin.String!类型

如何在协程之外获取 Flow 的值?

Android 上的 Kotlin:将map到list

在android java类中使用Kotlin扩展

Kotlin 错误:public function exposes its 'public/*package*/' return type argument