Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin top-levels functions vs object function

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?

like image 875
Vahan Avatar asked Feb 25 '19 09:02

Vahan


2 Answers

KotlinConf 2017 - You Can, but Should You? by Mike Gouline recommends we should use the top-level function carefully because it may cause "autocomplete pollution".

But, BTW, Andrey Breslav regarded the top-level function as his the most favorite language feature in KotlinConf 2018 - Closing Panel.

like image 85
Ray Eldath Avatar answered Oct 16 '22 13:10

Ray Eldath


The recommended practice is to never use object for creating namespaces, and to always use top-level declarations when possible. We haven’t found name conflicts to be an issue, and if you do get a conflict, you can resolve it using an import with alias.

like image 22
Alexey Romanov Avatar answered Oct 16 '22 13:10

Alexey Romanov