Kotlin alongside Java?

One of the amazing things about Kotlin is its ability to reside and work with Java in the same project.

Let's try creating a Kotlin class. The Android Studio Kotlin plugin makes this as easy as creating a Java class. Select File | New | Kotlin File/Class:

On the New Kotlin File/Class popup, enter the name of your class, select Class from the Kind dropdown, and click OK:

The new class looks like this:

package com.packtpub.eunice.tictactoe

class HelloKotlin {
}
The default visibility modifier in Kotlin is public, so there's no need to specify the public modifier like you would in a Java class.

Let's add the following method to our new Kotlin class:

fun displayMessage(view: View) {
Snackbar.make(view, "Hello Kotlin!!", Snackbar.LENGTH_LONG).setAction("Action", null).show()
}

The previous method takes an Android view (android.view.View) as a parameter and passes it along with a message to the Snackbar make() method to display the message. 

This ability of Kotlin to make use of Java code is called interoperability. This feature also works the other way round, allowing Kotlin code to be called from a Java class. Let's try that:

Open MainActivity.java. In the onCreate() method, replace the following line of code:

Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG).setAction("Action", null).show();

With the following:

new HelloKotlin().diplayMessage(view);

The preceding line of code creates an instance of the HelloKotlin class, and calls its displayMessage() method. 

Build and run your app:

Yes, it's that easy.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset