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

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

提交回复
热议问题