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
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?
I am still a bit confused the file organization in Java/Kotlin/Android projects.
Create a projectIn the left-hand panel, select Kotlin Multiplatform. Enter a project name, then in the Multiplatform section select Library as the project template. Select the Gradle DSL – Kotlin or Groovy. Specify the JDK, which is required for developing Kotlin projects.
To convert Java code to Kotlin, open the Java file in Android Studio, and select Code > Convert Java File to Kotlin File. Alternatively, create a new Kotlin file (File > New > Kotlin File/Class), and then paste your Java code into that file.
No, it just needs kotlin-stdlib as a dependency to use it from Java.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With