Why would you use apply in Kotlin?
Why would you use apply in Kotlin?
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:
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:
val person = Person("John Doe", 30).apply {
address = "123 Main St"
phoneNumber = "555-1234"
}
When working with builder patterns or fluent interfaces, apply can help you chain method calls together:
val button = Button(context).apply {
text = "Click me"
setOnClickListener { /* handle click */ }
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào