The following configuration scenarios are common in actual development:

  1. Existing modules support Kotlin
  2. New projects use pure Kotlin
  3. Kotlin tests the module

Let’s look at how to configure them.

Existing module Kotlin environment configuration

If an existing project needs to support Kotlin, complete the following steps.

  1. Versions below AS 3.0 require manual addition of the Kotlin plugin. 3.0 and later can skip this step. Add File — > Settings — > Plugins — > Browser Repositories — > Search for Kotlin, download, install, and restart.

  2. The project root directory configures the Kotlin version number and plug-ins.

Buildscript {// latest version of Kotlin ext.kotlin_version ='1.3.21'
    repositories {
        google()
        jcenter()
        
    }
    dependencies {
        classpath 'com. Android. Tools. Build: gradle: 3.4.0'// Introduce the Gradle plugin classpath"org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"}}Copy the code
  1. Build. gradle under Module adds plug-ins
// Compile kotlin code to apply plugin:'kotlin-android'// The findViewById apply plugin is not required:'kotlin-android-extensions'
Copy the code
  1. Build. gradle under module adds kotlin library dependencies.
dependencies {
    ...
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}
Copy the code

New Project Configuration

If you want to use Kotlin in a new Project, check Kotlin in the New Project procedure.

Kotlin test project

If you want to configure a Kotlin test Module using AS, create a Java Module and do the following.

Can Android Studio be used to run standard Java Projects?

Turn the Java Kotlin

AS provides conversion tools to convert Java code directly into Kotlin code

Also, if you copy a piece of Java code into a Kotlin file, the editor automatically inserts it into Kotlin code. This feature is very useful if you are not sure how to implement Kotlin syntax during the coding process, you can implement it in Java and copy it to a Kotlin file to find out.

Kotlin code corresponding Java source code

Sometimes you need to know the Java implementation of Kotlin code. You can use AS to convert Kotlin source files into Kotlin bytecodes, and then decompile Kotlin bytecodes into Java source files.

Tools — > Kotlin — > show Kotlin Bytecode

Click the Decompile button to view the Java source code.

By default, Kotlin’s Library or AAR is not available when it is introduced into the project. You can see some of the internal implementation details using this decomcompiler.