SnuKies
SnuKies

Reputation: 1723

Square brackets after function call

In the PagingWithNetworkSample, in the RedditActivity.kt on the line 68 is a function that contains another function call followed by square brackets and the class type (line 78):

private fun getViewModel(): SubRedditViewModel {
    return ViewModelProviders.of(this, object : ViewModelProvider.Factory {
        override fun <T : ViewModel?> create(modelClass: Class<T>): T {
            val repoTypeParam = intent.getIntExtra(KEY_REPOSITORY_TYPE, 0)
            val repoType = RedditPostRepository.Type.values()[repoTypeParam]
            val repo = ServiceLocator.instance(this@RedditActivity)
                    .getRepository(repoType)
            @Suppress("UNCHECKED_CAST")
            return SubRedditViewModel(repo) as T
        }
    })[SubRedditViewModel::class.java]
}

What does this exactly do? Automatically cast to that type? (it's not an array/list to suppose it calls get)

Can you bring an example where this is useful?

Upvotes: 6

Views: 972

Answers (1)

ordonezalex
ordonezalex

Reputation: 2744

That code might look strange, but it's really just a way of calling get(). This would be just as valid, but slightly more verbose:

private fun getViewModel(): SubRedditViewModel {
    return ViewModelProviders.of(this, object : ViewModelProvider.Factory {
        override fun <T : ViewModel?> create(modelClass: Class<T>): T {
            // ...
        }
    }).get(SubRedditViewModel::class.java)
}

Upvotes: 7

Related Questions