Kotlin's approach to anonymous classes

Sometimes we only need the object to modify some of the member data or to perform a small action. Java was doing this using anonymous inner classes. Kotlin has slightly modified and generalized the approach, and came up with object expressions.

Let's have a look at the following code:

CognitoUser?.getDetailsInBackground(object : GetDetailsHandler {    override fun onSuccess(details: CognitoUserDetails) {        // Successfully retrieved user details    }    override fun onFailure(exception: Exception) {        // Failed to retrieve the user details, probe exception for the cause    }})

GetDetailsHandler is an anonymous class used as an object expression.

Keep in mind that anonymous objects can be used as types only in local and ...

Get Hands-On Serverless Applications with Kotlin now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.