When we want to use Kotlin in Android Studio, it's quite simple. Add the kotlin dependent library, and also add the Kotlin-Android plugin as below
apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
However, if I have a normal library (Used to be Java), and want to write in Kotlin, should I add any plugin? The below definitely not working.
apply plugin: 'java-library'
apply plugin: 'kotlin-android'
There is no 'kotlin-library' that I find to add in. What should I add to my module gradle to have it able to compile Kotlin?
Kotlin is designed with Java interoperability in mind. Existing Java code can be called from Kotlin in a natural way, and Kotlin code can be used from Java rather smoothly as well.
Can I call Android or other Java language library APIs from Kotlin? Yes. Kotlin provides Java language interoperability. This is a design that allows Kotlin code to transparently call Java language methods, coupled with annotations that make it easy to expose Kotlin-only functionality to Java code.
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.
If your question is can you use kotlin files in java files and vice versa then the answer is yes.
You only need to add the Kotlin plugin:
apply plugin: "kotlin"
The java-library
plugin was only recently added to Gradle and extends the java
plugin. The naming does not expand to kotlin
though.
As it been said you need to add
apply plugin: 'kotlin'
but you also need to add at least
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
to your dependency section of kotlin library module, otherwise standard library kotlin features would not work. E.g. you won't have @JvmStatic
annotation, and so on.
The sample build.gradle
of kotlin
library module can look like this:
apply plugin: 'kotlin'
repositories {
mavenCentral()
}
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
}
$kotlin_version
should be defined in project build.gradle
file.
The sample is taken from library project in Idea and tested to work with Android Studio project (tested with Android Studio 3.0 Beta 2
) as a library dependency to an app
module.
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