Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Square brackets after function call

Tags:

kotlin

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?

like image 297
SnuKies Avatar asked Jun 28 '19 07:06

SnuKies


Video Answer


1 Answers

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)
}
like image 106
ordonezalex Avatar answered Dec 15 '22 05:12

ordonezalex