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 a difference between a class and object in Kotlin?

expert

How Kotlin coroutines are better than RxKotlin/RxJava?

middle

What is the equivalent of Java static methods in Kotlin?

Bình luận

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

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