Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 function outside 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 impossible! That's not how an object-oriented language works normally, right?

In the documentation, they talk of Local Functions for the classic function and Member Functions for the function defined inside a class or object but they don't explain when it's better to use one or the other.

like image 606
Jéwôm' Avatar asked Feb 27 '18 16:02

Jéwôm'


People also ask

Can a method be created outside of a class?

Yes you can definitely have functions outside of a class.

How do you write a function in Kotlin?

Before you can use (call) a function, you need to define it. To define a function in Kotlin, fun keyword is used. Then comes the name of the function (identifier). Here, the name of the function is callMe .

Why are Kotlin functions known as top level functions?

1. Top-Level Functions. Top-level functions are functions inside a Kotlin package that are defined outside of any class, object, or interface. This means that they are functions you call directly, without the need to create any object or call any class.

Can we write anything outside the class in Java?

In Java, there are only classes; nothing exists outside a class. Edit You can have public methods in non-public classes, but you probably don't want that since the non-public classes will have limited (perhaps none) visibility outside of the declaring class.


1 Answers

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.

like image 89
Marko Topolnik Avatar answered Oct 11 '22 10:10

Marko Topolnik