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

junior

How to initialize an array in Kotlin with values?

senior

What is Coroutine Scope and how is that different from Coroutine Context?

middle

What is the difference between open and public in Kotlin?

Bình luận

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

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