Câu hỏi phỏng vấn Kotlin
Câu hỏi

Why is there no stat...

Câu trả lời

In Kotlin, there is no direct equivalent to the static keyword found in languages like Java. Instead, Kotlin uses companion objects and top-level functions and properties to achieve similar functionality.

Here are a few reasons why Kotlin doesn't have a static keyword:

Companion Objects

Kotlin uses companion objects to provide a way to associate functions and properties with a class, without using the static keyword. A companion object is defined within a class and can access the private members of the class. It can be accessed using the class name, similar to how static members are accessed in Java.

kotlin Copy
class MyClass {
    companion object {
        fun myFunction() {
            println("This is a companion object function.")
        }
    }
}

fun main() {
    MyClass.myFunction() // Accessing the companion object function
}

Top-Level Functions and Properties

Kotlin allows you to define functions and properties directly at the top level of a file, outside of any class. These top-level declarations are essentially singletons and can be accessed from an...

senior

senior

Gợi ý câu hỏi phỏng vấn

junior

What is the difference between var and val in Kotlin?

middle

val mutableList vs var immutableList . When to use which in Kotlin?

junior

What is a primary constructor in Kotlin?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào