DisplayMessageActivity Kotlin missing import and declaration

Hello Kotlin people

I’ve been doing the developer.android tutorial (Build your first app  |  Android Basics  |  Android Developers)

In the DisplayMessageActivity file, Java version:

// Get the Intent that started this activity and extract the string
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

The corresponding snippet in the Kotlin version:

// Get the Intent that started this activity and extract the string
val message = intent.getStringExtra(EXTRA_MESSAGE)

So in Kotlin I don’t need to declare intent or to specify that EXTRA_MESSAGE comes from MainActivity?

Also in the Kotlin version I failed to import android.content.Intent in DisplayMessageActivity.kt and the app works fine?

I feel I understand what’s going on in Java but the Kotlin version confuses me a bit. Any help would be greatly appreciated!

As stated in the Kotlin Docs whenever Java setters and getters follow the java convention, they will be accessible in Kotlin via properties.

So if you have a java class:

public class SomeClass {
    private String name;
    public String getName() { return name; }
    public String setName(String name) { this.name = name; }
}

it will be accessible in Kotlin via a property:

val obj = SomeClass()
obj.name = "Hello"
println(obj.name)

In your case Activity has a setter and a getter for the intent, which will be accessible in Kotlin as property. As you don’t declare a local property with the intent, you don’t need to import its type.

The propper java code to the kotlin code you posted would actually be:

String message = getIntent().getStringExtra(MainActivity.EXTRA_MESSAGE);