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

前端 未结 3 1283
悲哀的现实
悲哀的现实 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.

提交回复
热议问题