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 is the purpose of Unit-returning in functions? Why is VALUE there? What is this V ALUE ?

expert

Why do we use companion object as a kind of replacement for Java static fields in Kotlin?

middle

What is the Kotlin double-bang !! operator?

Bình luận

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

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