Kotlin顶级函数与对象函数 [英] Kotlin top-levels functions vs object function

查看:776
本文介绍了Kotlin顶级函数与对象函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有静态功能,该功能仅限于某些上下文,例如仅适用于文档.有两种方法可以将其定义为顶级函数或对象中的函数.

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顶级函数与对象函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆