Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
160 views
in Technique[技术] by (71.8m points)

java - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...