Why is possible to write a function outside a class in Kotlin?

前端 未结 3 1279
悲哀的现实
悲哀的现实 2020-12-28 12:53

I don\'t understand why is possible to write a function outside a class in Kotlin ? Is that a good practice ?

For example, it\'s possible in Kotlin to write a funct

相关标签:
3条回答
  • 2020-12-28 13:19

    In Java, this is impossible! That's not how an object-oriented language works normally, right?

    Just stop for a second and reconsider the nature of java's static method. A class is supposed to be a blueprint for objects, describe their behavior and state. But you can call a static method without creating any instances.

    How does that fit into the object-oriented picture? How does a static method "belong" to the class it's declared in?

    Actually static methods are a hack in Java, they pollute and misuse the OOP notion of a class. But you got used to them over the years so you don't feel that anymore.

    Conceptually, a static method is a top-level function and Java uses the name of its declaring class as its namespace. In contrast to that, Kotlin allows you to declare top-level functions without misusing the class for namespacing.

    0 讨论(0)
  • 2020-12-28 13:28

    Yes, this is good practice. Kotlin is not a purely object-oriented language, so it's not obligated to follow how "an object-oriented language works normally" (even though other object-oriented languages, such as C++, Ruby and Python, also allow top-level functions).

    It's better to use a top-level function when the logic of this function does not clearly belong to any class.

    0 讨论(0)
  • 2020-12-28 13:36

    Yes, it is a good practice to create package-level functions if the function logic is independent of properties and lifecycle of a class. Example:

    • a function to convert miles per gallon to kilometers per litre is independent of any object and fits well as package-level.
    • otoh, a function to cancel reservation would naturally be associated with a specifc reservation object and fits well inside such a class.

    The main benefit of a package-level function is simplicity (ergo better maintainability): callers of your function don't need to declare and create an object to call the function. (If your package-level function needs to be called from Java code, this benefit is lost because the Java calling code has to use a class name that is generated by Kotlin.)

    IMPORTANT: Although you don't have a class lexical scope for your function, the Single-Responsibility Principle (SRP) still applies. Do not create a Kotlin source file, say Util.kt, and bloat it up with functions that lack cohesion, that is, functions that do unrelated things.

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