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

What are Object expressions i...

Câu trả lời

Object Expressions in Kotlin

In Kotlin, an object expression is a way to create an anonymous class instance on the fly. It is used when you need to create an object of a class with some modifications or additional functionality, without defining a separate class for it.

When to use Object Expressions

  1. Implementing an interface with some additional logic: You can create an object expression that implements an interface and provides its own implementation for the interface methods.

  2. Extending an existing class with some modifications: You can create an object expression that extends an existing class and overrides or adds new properties and methods.

  3. Creating a singleton-like object: Although Kotlin has a dedicated keyword for creating singletons (object declarations), you can use object expressions to create a singleton-like object with some additional logic or properties.

  4. Passing a function as an argument: You can use object expressions to create an instance of a class that implements a functional interface or a SAM (Single Abstract Method) interface, which is often used when passing a function as an argument to another function.

Example: Implementing an Interface with Additional Logic

kotlin Copy
int...
senior

senior

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

middle

Explain lazy initialization in Kotlin

middle

What is the difference between List and Array types?

senior

What is Coroutine Scope and how is that different from Coroutine Context?

Bình luận

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

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