Object expressions and declarations

Sometimes we need to create an object with a slight modification of some class, without explicitly declaring a new subclass for it.  Java handles this case with anonymous inner classes. Kotlin slightly generalizes this concept with object expressions and object declarations. Take a look at the following class:

    timelineService.showHomeTimeline().enqueue(object :      Callback<List<Tweet>>() {       override fun success(result: Result<List<Tweet>>) {         rvTimeline.layoutManager = LinearLayoutManager(context)         rvTimeline.adapter = TweetAdapter(result.data) {           startActivity<TweetDetailActivity>(TWEET_ID to it.id)        }       }        override fun failure(exception: TwitterException) {          toast(exception.message.toString())        }    })

The object

Get Kotlin Blueprints 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.