If you’re thinking about starting an Android project using Kotlin (what is definitively legitimate, some would actually call Kotlin the next generation of Java) – just do it! The setup will be faster than your considerations!

Install the Kotlin Plugin

For installing the Kotlin Plugin, first open Android Studio and start a new Android Studio project with your standard configuration (name your project, choose Android version… Nothing special). You need this plugin to configure Kotlin, converting existing Java classes into Kotlin classes, or even creating new Kotlin files very easily…

Go to File / Settings / Plugins / Install JetBrains plugin… / Kotlin and click Install.

Choose Kotlin Plugin

Restart Android Studio for getting your plugin ready.

Convert Java classes

Now it’s really easy to create your first Kotlin class. Open the MainActivity.java you’ve created while setting up your Android project:

  • Press Ctrl+Shift+A (Find Action Menu)
  • Choose Convert Java File To Kotlin File

Convert Java To Kotlin

Your MainActivity.kt (notice the change from *.java to *.kt) should now look like this:

Congrats!

Create new files

Of course the creation of a new Activity or class file is just as simple:

  • Type Kotlin File in the Find Action Menu.
  • Choose name as well as kind of file.

Configure your project

When you try to build your project, Android Studio is smart enough to notify you that Kotlin is not yet configured.

Simply click Configure and choose the latest available Kotlin version. This automatically adds new lines in your build.gradle files.

The project’s build file

In the project‘s build.gradle file the currently used kotlin_version is defined under the buildscript section:

In addition the kotlin gradle plugin dependency was added here:

The module’s build file

In the module‘s build.gradle file you can notice the insertion of the plugin:

as well as the dependency on the kotlin standard library:

As an aside, it is recommended to rename your java source folder to ‘kotlin’ (because your source code is written in Kotlin).
Additionally you need to add the following line under the android section to indicate the kotlin directory as source root:

Project sync

Changes on the build files cause a resync of the project. Android Studio gives you a notification of it, so you can simply press Sync Now. Note that as always you can also invoke it through the Find Action Menu (Ctrl+Shift+A) by typing Sync Project with Gradle Files.

Gradle knows now how to compile your code. Perfect!

Build it – run it – start using Kotlin!

Leave a Comment

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close