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

I don’t understand why it is possible to write a function outside the class in Kotlin? Is this a good practice?

For example, in Kotlin, you can write a function outside of my MainActivity class:

 fun hello(){} class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) hello() } } 

In Java, this is not possible! It's not like an object oriented language works fine, right?

In the documentation, they talk about Local functions for a classic function and Member functions for a function defined inside a class or object, but they do not explain when it is better to use one or the other.

+5
source share
2 answers

In Java, this is not possible! It's not like an object oriented language works fine, right?

Just stop for a second and rethink the nature of the static java method. It is assumed that the class is a plan for objects, describes their behavior and state. But you can call the static method without creating any instances.

How does this fit into an object-oriented picture? How does a static method "belong" to the class in which it was declared?

In fact, static methods are a hack in Java, they pollute and misuse the concept of an OOP class. But you have become accustomed to them for many years so that you no longer feel this.

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

+10
source

Yes, this is a good practice. Kotlin is not a purely object-oriented language, so it is not required to follow how the “object-oriented language works fine” (although other object-oriented languages, such as C ++, Ruby and Python, also allow you to perform top-level functions) .

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

+8
source

Source: https://habr.com/ru/post/1275608/


All Articles