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

Why would you use apply in Kotlin?

Câu trả lời

Here is an answer to the Kotlin interview question "Why would you use apply in Kotlin?":

The apply function in Kotlin is a scope function that allows you to perform a series of operations on an object and then return the object itself. It is particularly useful in the following scenarios:

Initializing Objects

When creating an object, you often need to set multiple properties. Using apply allows you to set these properties in a more concise and readable way:

kotlin Copy
val person = Person("John Doe", 30).apply {
    address = "123 Main St"
    phoneNumber = "555-1234"
}

Chaining Method Calls

When working with builder patterns or fluent interfaces, apply can help you chain method calls together:

kotlin Copy
val button = Button(context).apply {
    text = "Click me"
    setOnClickListener { /* handle click */ }
    layoutParams = ViewGroup.LayoutParams(
        ViewGroup.LayoutParams.WRAP...
middle

middle

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

junior

What is basic difference between fold and reduce in Kotlin? When to use which?

expert

How Kotlin coroutines are better than RxKotlin/RxJava?

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