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

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 top-level functions and the class only provides a namespace for them. Speaking strictly from the OOP perspective you bring up, they are a hack. But you got used to them over the years so you don’t feel that anymore.

In contrast to that, Kotlin allows you to declare top-level functions without forcing you to couple their name to a class. Sometimes you expressly want to couple a top-level function to a class, and that’s what companion objects are for in Kotlin.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)