为什么可以在 Kotlin 的类之外编写函数? [英] Why is possible to write a function outside a class in Kotlin?
问题描述
我不明白为什么可以在 Kotlin 的类之外编写函数?这是一个好习惯吗?
I don't understand why is possible to write a function outside a class in Kotlin ? Is that a good practice ?
例如,在 Kotlin 中可以在我的 MainActivity
类之外编写一个函数:
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()
}
}
在 Java 中,这是不可能的!这不是面向对象语言的正常工作方式,对吧?
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.
推荐答案
是的,创建包级函数是一个好习惯如果函数逻辑是独立的类的属性和生命周期.示例:
Yes, it is a good practice to create package-level functions if the function logic is independent of properties and lifecycle of a class. Example:
- 将每加仑英里数转换为每升公里数的函数独立于任何对象,并且非常适合包装级别.
- otoh,取消预订的函数自然会与特定的预订对象相关联,并且非常适合这样的类.
包级函数的主要好处是简单(因此具有更好的可维护性):函数的调用者不需要声明和创建对象来调用函数.(如果你的包级函数需要从 Java 代码中调用,这个好处就失去了,因为 Java 调用代码必须使用 Kotlin 生成的类名.)
The main benefit of a package-level function is simplicity (ergo better maintainability): callers of your function don't need to declare and create an object to call the function. (If your package-level function needs to be called from Java code, this benefit is lost because the Java calling code has to use a class name that is generated by Kotlin.)
重要提示:虽然您的函数没有类词法范围,但单一职责原则 (SRP) 仍然适用.不要创建 Kotlin 源文件,比如 Util.kt,并用缺乏内聚力的函数来膨胀它,即做不相关的事情的函数.
IMPORTANT: Although you don't have a class lexical scope for your function, the Single-Responsibility Principle (SRP) still applies. Do not create a Kotlin source file, say Util.kt, and bloat it up with functions that lack cohesion, that is, functions that do unrelated things.
这篇关于为什么可以在 Kotlin 的类之外编写函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!