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

How would you create a singleton with parameter in Kotlin?

Câu trả lời

Here's how you can create a singleton with a parameter in Kotlin:

Singleton with Parameter in Kotlin

To create a singleton with a parameter in Kotlin, you can use the object keyword along with a constructor parameter. Here's an example:

kotlin Copy
class MySingleton(val parameter: String) {
    companion object {
        @Volatile
        private var instance: MySingleton? = null

        fun getInstance(parameter: String): MySingleton {
            return instance ?: synchronized(this) {
                instance ?: MySingleton(parameter).also { instance = it }
            }
        }
    }

    // Other singleton methods and properties
}

In this example:

  1. We define a class MySingleton that takes a parameter of type String in its constructor.

  2. Inside the class, we use the companion object to hold the singleton instance.

  3. We declare a @Volatile variable instance of type MySingleton? (nullable `MySing...

middle

middle

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

middle

What is the difference between open and public in Kotlin?

middle

What is the difference between List and Array types?

junior

What is the difference between var and val in Kotlin?

Bình luận

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

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