Kotlin top-levels functions vs object function

前端 未结 5 1476
余生分开走
余生分开走 2021-01-19 01:20

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

相关标签:
5条回答
  • 2021-01-19 01:45

    object Clazz will be compiled as singleton, top-level function will be compiled as static in JVM.

    if there are no reasons for your method to be in instance, static(top-level, companion object) way would be a little bit high-performance.(ref: https://stackoverflow.com/a/11993118/5354658)

    0 讨论(0)
  • 2021-01-19 01:46

    Tip for multi-module projects:

    Use the internal visibility modifier to scope a top-level function to its containing module so that it doesn't pollute the IDE auto-complete in unrelated modules.

    // module A
    internal fun doSomething() {
        // ...
    }
    
    // module B
    doSomething() // (!) Cannot access 'doSomething': it is internal in module A
                  // Does NOT show up in module B's auto-complete
    
    0 讨论(0)
  • 2021-01-19 01:54

    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.

    0 讨论(0)
  • 2021-01-19 01:56

    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.

    0 讨论(0)
  • 2021-01-19 02:01

    Although the recommended approach is to use top-level declarations when possible, functions that are only used in specific contexts should be scoped to that context and declared in the relevant class. Top-level functions are especially useful for defining helper or utility functions. An example would be the functions of collections in the Java standard library, that have a truly global scope. The same applies to constants. Read the discussion under this answer https://stackoverflow.com/a/48820895/1635488

    In your case, DocPrefManager has a specific context. Also, I guess you don't want to pollute IDE auto-completion list with specific functions. It leads to unmaintainability.

    P.S. DocPrefManager functions shouldn't depend on App.getContext(). DocPrefManager class should be initialized with a context and in that case using top-level functions is odd, cause your functions wouldn't be static.

    0 讨论(0)
提交回复
热议问题