Search code examples
androidandroid-studiokotlin

Create a Kotlin library in Android Studio


I am very new to both the Android and JVM platforms. Using Android Studio, I would like to create an Android app and put most of my business logic in a library. I would also like to just use Kotlin, no Java.

When I go to File > New Module, the options listed are

  • Phone & Tablet module
  • Android Library
  • Instant App
  • Feature Module
  • Android Wear Module
  • Android TV Module
  • Android Things Module
  • Import Gradle Project
  • Import Eclipse ADT Project
  • Import .JAR/.AAR Package
  • Java Library

I can create a Kotlin-based library with the Android Library option, but this also includes a lot of files for dealing with resources and controls.

I just want a pure Kotlin library. What is the easiest way to create one?

  • Can I delete a portion of an Android Library?
  • Can I change some settings in a Java Library?
  • Can I download a plugin that will just give me the option to create a Kotlin library?

I am still a bit confused the file organization in Java/Kotlin/Android projects.


Solution

  • You need a module with no Android dependencies and resources - this is what a Java library module does, so you start by creating one of those. From there, you just need to enable Kotlin inside this module.

    The build.gradle file you get when you create your module is something like this:

    apply plugin: 'java-library'
    
    dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
    }
    

    You need to add the Kotlin plugin and standard library. If you don't have the mavenCentral repository added for all modules in your project yet, you need to add that as well:

    apply plugin: 'java-library'
    apply plugin: 'kotlin'
    
    dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
        implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    }
    
    repositories {
        mavenCentral()
    }
    

    This is assuming that you have a kotlin_version declared in your project level build.gradle file, which is the usual way for Android projects, and I believe that's how Android Studio configures a project if you tick the checkbox to use Kotlin.


    With those changes to your library's build.gradle, you can remove the automatically generated MyClass.java file from your library's source folder (/src/main/java/your/package/name), and start adding Kotlin files instead. If you'd like, you can also rename the /src/main/java folder to /src/main/kotlin. Or you can use both folders, this is entirely up to you.