After reading a lot of different posts raving about Kotlin, I couldn’t help myself. I had some serious FOMO. In this blog post, I will be looking at getting Kotlin set up in existing Android Apps.

What is Kotlin?

Kotlin is a statically typed programming language that can be used to write Android Apps. It is made by JetBrains, the same guys who make IntelliJ, Resharper and other awesome tools.

What does Kotlin code look like?

Below is how you would declare a function in Kotlin:

fun sum(a: Int, b: Int): Int { return a + b }

As you can see there are a few notable differences from Java:

The lack of semicolons (Yay right?). The declaration of the return type is at the end of the function definition. The type of the parameters are defined after the parameter name.

For more basic syntax differences, you can read more here.

Why is it better than Java?

A quick summary of Kotlin’s Advantages over Java:

This video by Jake Wharton highlights the differences between Java and Kotlin quite well. There are more links at the end of this blog post.

So now that we know what Kotlin is and why we might want to use it for our Android Apps. Lets take a look at getting set up in our existing Android Project.

Setting up your existing Android Project to use Kotlin

Install the Kotlin plugin for Android Studio : Go to “Preferences”→ “Plugins”→ “Install JetBrains Plugin”→ Type “Kotlin” in the search box→ Select “Kotlin” and install it. You will probably need to restart Android Studio for the settings to take effect. Go to your project level build.gradle file and add the following line into the classpath section buildscript { repositories { jcenter() } dependencies { classpath "com.android.tools.build:gradle:2.0.0-alpha3" classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.0.0-beta-4584" } } In your app level build.gradle add the following: buildscript { repositories { maven { url 'https://maven.fabric.io/public' } } dependencies { classpath 'io.fabric.tools:gradle:1.+' } } apply plugin: 'com.android.application' apply plugin: 'kotlin-android' android { ... sourceSets { main.java.srcDirs += 'src/main/kotlin' } } dependencies { ... compile 'org.jetbrains.kotlin:kotlin-stdlib:1.0.0-beta-4584' } Create a folder in your app/src/main/ folder called kotlin . You can then create a folder with your package name, so for my example it would be org.bookdash.android. (You can also add kotlin files into the same directory as the Java files, I just prefer to separate them out by language.)

To add a new Kotlin class, right click on the package name and click “New -> Kotlin File or class”. Give it a name, select the type and you can start writing Kotlin code!

Convert existing Java files to Kotlin

In Android Studio if you want to convert a Java class to Kotlin, do the following:

Open the file you wish to convert Run the following command. (Navigate to Action): MacOs: CMD + Shift + A

Linux & Windows: CNTRL + Shift + A Then type “kotlin”, you should see the option to convert existing Java file into Kotlin. This will take the Java file that you are in and convert it into a Kotlin class. I would make sure that the code that is generated is okay. I am always a bit worried about generated code not working. 😁 I converted the AboutActivity from my Book Dash App to use Kotlin, this is the result: class AboutActivity : BaseAppCompatActivity(), AboutContract.View { private var aboutPresenter: AboutPresenter? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_about) aboutPresenter = AboutPresenter(this) val toolbar = findViewById(R.id.toolbar) as Toolbar setSupportActionBar(toolbar) val actionBar = supportActionBar if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true) actionBar.setTitle(R.string.about_heading) } val textViewWhyBookDash = findViewById(R.id.text_why_bookdash) as TextView textViewWhyBookDash.text = Html.fromHtml(getString(R.string.why_bookdash)) Linkify.addLinks(textViewWhyBookDash, Linkify.ALL) ... } override fun showLearnMorePage(url: String) { val intent = Intent(Intent.ACTION_VIEW) intent.setData(Uri.parse(url)) startActivity(intent) } } If you want to see an example of an app using Kotlin and Java, you can check out my github project, the Feature-Kotlin-AboutActivity branch.

Writing Tests in Kotlin

After getting some code written in Kotlin, I thought it would be great to see if I could set up some Android tests in Kotlin. Here is how to do it:

In your androidTest folder create a kotlin folder Create your package name that matches the package you are testing. In your app build.gradle file, add the following: android { ... sourceSets { main.java.srcDirs += 'src/main/kotlin' androidTest.java.srcDirs += 'src/androidTest/kotlin' } } Adding that line tells Gradle that it should also look in the kotlin folder for source code and it should include it when building. Then you can start adding code to that folder. Below is an example of my AboutActivityTest which does some basic espresso testing in Kotlin. @RunWith(AndroidJUnit4::class) @SmallTest class AboutActivityTest { @Rule fun getRule() = ActivityTestRule(AboutActivity::class.java) @Before fun setUp() { Intents.init() } @After fun tearDown() { Intents.release() } @Test @Throws(Throwable::class) fun loadAboutBookDash_SeeInformation() { val about = Html.fromHtml(InstrumentationRegistry.getTargetContext().getString(R.string.why_bookdash)) val headingAbout = InstrumentationRegistry.getTargetContext().getString(R.string.heading_about) onView(withText(headingAbout)).check(matches(isDisplayed())) onView(withText(about.toString())).perform(scrollTo()).check(matches(isDisplayed())) } @Test @Throws(Throwable::class) fun clickLearnMore_OpenBrowser() { onView(withText(R.string.learn_more)).perform(scrollTo(), click()) intended(allOf(hasAction(Intent.ACTION_VIEW), hasData(Uri.parse("http://bookdash.org")))) } } Why I like Kotlin

The code looks neater and concise (no more semi-colons)

It is not just for Android apps. It runs on the JVM you can use it pretty much anywhere.

You can write in both Java and Kotlin in the same project, they work together.

Of course the Null Safety , Lambdas , Extension functions are great too 😁

What next?

I suggest reading through the docs about the advantages of Kotlin and try out some Kotlin code on the website or in a sample app. Then go forth and #MakeKotlinApps!

I would love to know what your are experiences with it so far? Do you have any other tips or tricks to getting started with Kotlin?

Links:

Book Dash Android App Github

Why Kotlin is my next Programming Language

Kotlin – The swift of Android

Using Project Kotlin for Android

RedChain – Github Project for Android App – Daily goal tracker written in Kotlin