为什么可以在Kotlin的类外部编写函数? [英] Why is possible to write a function outside a class in Kotlin?

查看:164
本文介绍了为什么可以在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?

在文档中,他们将 Local Functions 用于经典功能,将 Member Functions 用于在类或对象中定义的功能,但是他们不解释何时使用最好使用其中一个.

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.

推荐答案

在Java中,这是不可能的!那不是面向对象语言正常工作的方式,对吗?

In Java, this is impossible! That's not how an object-oriented language works normally, right?

请稍等片刻,然后重新考虑Java静态方法的性质.类应该是对象的蓝图,描述对象的行为和状态.但是您可以调用静态方法而无需创建任何实例.

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?

实际上,静态方法是Java中的一种技巧,它们污染并滥用了类的OOP概念.但是这些年来,您已经习惯了它们,所以您不再有这种感觉了.

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.

从概念上讲,静态方法是顶级函数,Java使用其声明类的名称作为其命名空间.与此相反,Kotlin允许您声明顶级函数而不会将类误用为命名空间.

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.

这篇关于为什么可以在Kotlin的类外部编写函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆