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

How are extensions resolved in Kotlin and what doest it mean?

expert

What is a motivation to make classes final by default in Kotlin? Do you agree with that decision?

middle

How would you create a singleton with parameter in Kotlin?

Bình luận

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

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