Question
I have this Java code in an Android activity:
CopyMaterialDialog builder = new MaterialDialog.Builder(MainActivity.this);
I want to convert this to Kotlin and correctly access the MainActivity instance. The automatic Java-to-Kotlin conversion does not handle MainActivity.this properly. How can I write the Kotlin equivalent, and how does activity context access work in Kotlin?
Short Answer
By the end of this page, you will understand how to replace MainActivity.this when converting Java Android code to Kotlin. You will learn when to use this, when to use this@MainActivity, why Android APIs often need an Activity or Context, and how to avoid common mistakes when working inside lambdas, inner classes, and builders.
Concept
In Java Android code, MainActivity.this means “the current instance of MainActivity.” It is often passed to APIs that need an Android Context, such as dialogs, adapters, intents, and UI components.
In Kotlin, the equivalent is usually one of these:
this
or, when you need to be explicit about which this you mean:
this@MainActivity
This matters because Kotlin has clearer rules for receivers and scopes. Inside a simple activity method, this usually already refers to the activity. But inside nested scopes such as lambdas, anonymous objects, or extension functions, this may refer to something else. In those cases, this@MainActivity tells Kotlin exactly which outer object you want.
In Android, an Activity is also a Context, so passing the activity instance is a common pattern. Many APIs need context to:
- create dialogs
- inflate layouts
- start activities
- access resources
- interact with the current UI theme
So the real concept here is not just syntax conversion. It is understanding how Kotlin refers to the current object and outer objects, especially in Android code where context types matter.
Mental Model
Think of this as saying: “me, the object currently speaking.”
In Java:
MainActivity.thismeans: “not just anythis, but thethisbelonging toMainActivity.”
In Kotlin:
thismeans: “the current object”this@MainActivitymeans: “thethisfrom theMainActivityscope”
Imagine you are inside a building with several rooms:
thismeans “the room I am currently standing in”this@MainActivitymeans “go back to the MainActivity room specifically”
This becomes useful when nested code creates a new scope and this changes meaning.
Syntax and Examples
In a normal activity method, Java code like this:
MaterialDialog.Builder builder = new MaterialDialog.Builder(MainActivity.this);
usually becomes this in Kotlin:
val builder = MaterialDialog.Builder(this)
If you want to be explicit, write:
val builder = MaterialDialog.Builder(this@MainActivity)
Basic example
class MainActivity : AppCompatActivity() {
fun showDialog() {
val builder = MaterialDialog.Builder(this)
builder.title(text = "Hello")
builder.show()
}
}
Here, this refers to the MainActivity instance because the code is directly inside the activity.
Example inside a nested scope
Sometimes this may no longer point to the activity:
class MainActivity : AppCompatActivity() {
fun showDialog() {
val runnable = Runnable {
val builder = MaterialDialog.Builder(this@MainActivity)
}
}
}
Using this@MainActivity makes it clear that you want the activity instance, not some other receiver.
Another common Android example
val intent = Intent(this, DetailsActivity::class.java)
startActivity(intent)
This works because this is the current activity, which is also a valid Context.
Step by Step Execution
Consider this Kotlin code:
class MainActivity : AppCompatActivity() {
fun showDialog() {
val builder = MaterialDialog.Builder(this)
builder.title(text = "Welcome")
builder.show()
}
}
Step by step:
class MainActivity : AppCompatActivity()creates an Android activity class.showDialog()is a method inside that activity.- Inside
showDialog(),thisrefers to the currentMainActivityobject. MaterialDialog.Builder(this)receives the activity as a context.builder.title(...)configures the dialog.builder.show()displays it on the screen.
Now compare with a nested case:
class MainActivity : AppCompatActivity() {
fun example() {
val listener = object : View.OnClickListener {
override fun onClick(v: View?) {
val builder = MaterialDialog.Builder(this@MainActivity)
}
}
}
}
Here is what changes:
object : View.OnClickListenercreates an anonymous object.- Inside
onClick, plainthisrefers to the listener object. - But
MaterialDialog.Builder(...)needs the activity context. - So
this@MainActivityexplicitly refers to the outer activity instance.
That is the key Kotlin idea: this depends on the current scope.
Real World Use Cases
This concept appears often in Android development.
Showing dialogs
AlertDialog.Builder(this)
Dialogs usually need an activity-themed context.
Starting another activity
val intent = Intent(this, ProfileActivity::class.java)
startActivity(intent)
The current activity is passed as the context.
Creating adapters or UI helpers
val adapter = MyAdapter(this)
Adapters often need context for layout inflation or resource access.
Accessing resources in scoped code
Inside lambdas or listeners, you may need:
this@MainActivity.getString(R.string.app_name)
Building Android components with the right theme
Using the activity context instead of the application context can matter when:
- showing dialogs
- using themed layouts
- applying activity-specific styling
Real Codebase Usage
In real Android projects, developers usually rely on a few common patterns.
1. Use this in simple activity code
If the code is directly inside an activity method, this is enough.
val dialog = AlertDialog.Builder(this)
2. Use this@MainActivity in nested scopes
This is common inside:
- click listeners
- anonymous objects
- extension-function receivers
- nested builder blocks
button.setOnClickListener {
val intent = Intent(this@MainActivity, DetailsActivity::class.java)
startActivity(intent)
}
3. Prefer the narrowest correct context
Developers choose the most appropriate context for the job:
thisorthis@MainActivityfor UI work tied to the activityapplicationContextfor app-wide work not tied to UI
4. Use guard clauses before UI actions
If an activity may be finishing or destroyed, codebases often guard against unsafe UI calls.
if (isFinishing) return
AlertDialog.Builder(this)
.setMessage("Done")
.show()
5. Be explicit when readability matters
Even if plain this works, some teams prefer this@MainActivity because it makes intent obvious in nested code.
That improves maintenance, especially in large files with multiple scopes.
Common Mistakes
Mistake 1: Using Java syntax directly in Kotlin
Broken code:
val builder = MaterialDialog.Builder(MainActivity.this)
Why it fails:
MainActivity.thisis Java syntax, not Kotlin syntax.
Fix:
val builder = MaterialDialog.Builder(this)
or:
val builder = MaterialDialog.Builder(this@MainActivity)
Mistake 2: Using the wrong this inside nested scopes
Broken code:
val listener = object : View.OnClickListener {
override fun onClick(v: View?) {
val builder = MaterialDialog.Builder(this)
}
}
Why it fails:
- Here,
thisrefers to the listener object, not the activity.
Fix:
val listener = object : View.OnClickListener {
override fun onClick(v: View?) {
val builder = MaterialDialog.Builder(this@MainActivity)
}
}
Mistake 3: Using applicationContext for dialogs
Broken code:
val builder = AlertDialog.Builder(applicationContext)
Why it is a problem:
- Dialogs usually need an activity context with the correct UI theme.
Fix:
val builder = AlertDialog.Builder(this)
Mistake 4: Assuming lambdas always change this
In Kotlin, lambdas do not always introduce a new this. It depends on the function and receiver type.
Avoid confusion by checking the current scope and using this@MainActivity when necessary.
Mistake 5: Passing a context that can outlive the activity incorrectly
Holding a reference to an activity for too long can cause leaks.
Avoid storing activity references in long-lived objects unless necessary.
Comparisons
| Situation | Java | Kotlin |
|---|---|---|
| Current activity in simple activity code | MainActivity.this | this |
| Explicit outer activity reference | MainActivity.this | this@MainActivity |
| Generic context variable | Context context | val context: Context |
| Application-level context | getApplicationContext() | applicationContext |
this vs this@MainActivity
| Form | Use when | Example |
|---|---|---|
this | The current scope is the activity | AlertDialog.Builder(this) |
this@MainActivity | You need to explicitly reference the activity from a nested scope | Intent(this@MainActivity, DetailsActivity::class.java) |
Activity context vs application context
| Context type | Good for | Avoid for |
|---|---|---|
| Activity context | dialogs, themed UI, inflating activity-related views | long-lived background objects |
| Application context | app-wide utilities, services, non-UI work | most dialog and themed UI creation |
Cheat Sheet
// Java
MainActivity.this
// Kotlin, inside MainActivity
this
// Kotlin, explicit outer activity reference
this@MainActivity
Quick rules
- Use
thiswhen you are directly inside the activity. - Use
this@MainActivitywhen another scope changes whatthismeans. - An
Activityis aContext. - Prefer activity context for dialogs and UI-related components.
- Prefer
applicationContextfor app-wide non-UI work.
Common conversions
// Java
new AlertDialog.Builder(MainActivity.this)
// Kotlin
AlertDialog.Builder(this)
// Java
Intent intent = new Intent(MainActivity.this, NextActivity.class);
// Kotlin
val intent = Intent(this, NextActivity::class.java)
Nested scope pattern
button.setOnClickListener {
val dialog = AlertDialog.Builder(this@MainActivity)
}
Remember
If Kotlin says the type is wrong for this, check whether you are in a nested scope and need this@YourActivityName.
FAQ
What is the Kotlin equivalent of MainActivity.this?
Usually this. If you need to be explicit in a nested scope, use this@MainActivity.
Why does MainActivity.this not work in Kotlin?
Because it is Java syntax. Kotlin uses labels like this@MainActivity instead.
When should I use this@MainActivity instead of this?
Use it when plain this refers to something else, such as an anonymous object or another receiver scope.
Is this in an activity the same as a Context?
Yes. An activity is a subtype of Context, so it can be passed where a Context is required.
Should I use applicationContext instead of this?
Only when you need an application-level context. For dialogs and many UI tasks, use the activity context.
Why does dialog code often need the activity instead of the application context?
Because dialogs usually depend on the current window and theme, which come from the activity.
Does every lambda change the meaning of this in Kotlin?
No. It depends on the kind of lambda and whether there is a receiver. If unsure, use this@MainActivity for clarity.
Mini Project
Description
Build a small Android activity that shows a dialog when a button is clicked. The purpose is to practice passing the correct activity context in Kotlin and to see when this and this@MainActivity are used.
Goal
Create an activity that opens a dialog from both a normal activity method and a nested click/listener scope using the correct Kotlin context reference.
Requirements
- Create a
MainActivityclass in Kotlin. - Add a function that shows a dialog using the activity context.
- Add a button click handler that also shows a dialog.
- Use
thisin the simple activity method. - Use
this@MainActivityin a nested scope where explicit activity access improves clarity.
Keep learning
Related questions
Accessing Kotlin Extension Functions from Java
Learn how Kotlin extension functions are compiled and how to call them correctly from Java with clear examples and common pitfalls.
Add a Maven Repository URL in Gradle Kotlin DSL (build.gradle.kts)
Learn how to add Maven Central and a custom Maven repository URL in Gradle Kotlin DSL using build.gradle.kts syntax.
Allow HTTP and HTTPS in Android 9 Pie with Network Security Configuration
Learn how Android 9 Pie handles cleartext HTTP traffic and how to allow HTTP and HTTPS safely using network security config.