Setting up Kotlin in Android Studio

We strongly encourage you to use Android Studio 3.0 for Android development, irrespective of whether you're using Kotlin or not. Android Studio 3.0 is the latest version of Android Studio, with a lot of bug fixes, new features, and improved Gradle build time.

For Android Studio 3.0, you don't need to do any setup to use Kotlin for Android development. You just need to select Include Kotlin support while creating a new project. Here is a screenshot for your reference:

We've highlighted the Include Kotlin support section of the Android Studio—Create Android Project dialog.

However, if you're using Android Studio 2.3.3, then follow these steps:

  1. Go to Android Studio | Settings | Plugins.
  2. Search for Kotlin (take a look at the following screenshot) and install that plugin as follows:
  1. Start a new Android project.
  2. To apply the Kotlin plugin to the project, open the project level build.gradle and modify the content, as shown here:
  1. Open the build.gradle in your module (or we might say, app level build.gradle) and add the following dependencies:
      compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version" 

You are now all set to start writing Kotlin code in Android Studio.

However, before starting with the Kotlin code, let's first review our build.gradle. The preceding code that I showed for Android Studio 2.3.3 is valid for Android Studio 3.0 as well, you just don't have to manually add this as Android Studio 3.0 automatically adds it for you. However, what is the purpose of those lines? Let's inspect them.

In the project level build.gradle file, the ext.kotlin_version = "1.1.51" line creates a variable in Gradle with the name of kotlin_version; this variable will hold a String value, 1.1.51 (which is the latest version of Kotlin at the time of writing this book). We are writing this in a variable, as this version is required in a number of places in the project level and app level build.gradle file. If we declare it once and use it in multiple places, then there will be consistency, and there won't be any chance for human mistakes.

Then, on the same file (project level build.gradle), we will add classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version". This will define a classpath used by Gradle to search for kotlin-jre when we add them as a dependency.

Inside the app level build.gradle file, we will write implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version".

So, let's get started with the Kotlin code. As we mentioned in the previous chapter, we will create a ToDoApp. There will be three screens, one for the ToDo List, one to create a ToDo, and one to edit/delete ToDo.

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

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