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

How is it recommended to create constants in Kotlin?

Câu trả lời

Here are a few recommended ways to create constants in Kotlin:

Using the const keyword

For primitive types and String, you can use the const keyword to define compile-time constants. These constants must be top-level or inside an object declaration.

kotlin Copy
const val PI = 3.14159
const val TAG = "MyApp"

Using object declarations

You can define constants inside an object declaration, which creates a singleton object.

kotlin Copy
object Constants {
    const val PI = 3.14159
    const val TAG = "MyApp"
}

To access these constants, use Constants.PI or Constants.TAG.

Using companion object

Inside a class, you can define constants in a companion object. This is useful when the constants are related to the class.

kotlin Copy
class MyCl...
middle

middle

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

middle

What are some disadvantages of Kotlin?

senior

What are Object expressions in Kotlin and when to use them?

expert

How does the reified keyword in Kotlin work?

Bình luận

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

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