Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the code this@MainActivity mean?

Tags:

android

kotlin

I'm a beginner of Kotlin, the following code is from a webpage, I can't understand that the parameter this@MainActivity in the code layoutManager = LinearLayoutManager(this@MainActivity), Could you tell me? Thanks!

import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.Menu
import android.view.MenuItem
import kotlinx.android.synthetic.main.activity_main.*
import mobi.porquenao.poc.kotlin.R

class MainActivity : BaseActivity() {
    lateinit var listAdapter: MainAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        with (list) {
            setHasFixedSize(true)
            layoutManager = LinearLayoutManager(this@MainActivity)
            listAdapter = MainAdapter()
            adapter = listAdapter
        }
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.main, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        listAdapter.add()
        list.smoothScrollToPosition(0)
        return true
    }

}
like image 389
HelloCW Avatar asked Aug 04 '17 09:08

HelloCW


1 Answers

It is a qualified this, used to access MainActivity's context from an outer scope.

class MainActivity {
    fun onCreate() {
        val list = listOf(1, 2, 3)
        with (list) {
            println(this)              // >>> [1, 2, 3]
            println(this@MainActivity) // >>> MainActivity@2a84aee7
        }
    }
}

You can read more about this approach in Kotlin documentation.

like image 143
Alexander Romanov Avatar answered Oct 09 '22 01:10

Alexander Romanov