Problem Statement
What are object expressions (anonymous objects) and when should you use them?
Explanation
Object expressions create anonymous objects on the fly using object colon Type syntax, useful for implementing interfaces, extending classes, or creating objects without declaring a named class. They can access and modify variables from their enclosing scope unlike Java anonymous classes which have restrictions, making them more powerful for closures and callbacks.
Use object expressions for one-off implementations like event listeners in Android, temporary adapters or comparators, or when you need to override methods in a single location without creating a separate class. Object expressions can implement multiple interfaces, extend a single class, and add extra properties or methods not in the implemented interfaces or superclass.
The key difference from object declarations is that object expressions create new instances each time they're evaluated, while object declarations are singletons. For type safety, if an object expression is used as a local or private declaration its type is the anonymous type, but if returned from public functions or assigned to public properties, its type is the declared supertype making additional members inaccessible.