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

middle

val mutableList vs var immutableList . When to use which in Kotlin?

middle

What are coroutines in Kotlin?

middle

May you briefly compare Kotlin vs Java?

Bình luận

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

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