Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add Kotlin support for normal Java Lib in Android?

Tags:

android

kotlin

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?

like image 313
Elye Avatar asked Aug 14 '17 11:08

Elye


People also ask

Can I use Java library in Kotlin Android?

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 you use any Java library in Kotlin?

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.

How do I add Kotlin to an existing Java project?

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.

Can I use both Java and Kotlin for Android?

If your question is can you use kotlin files in java files and vice versa then the answer is yes.


2 Answers

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.

like image 139
tynn Avatar answered Sep 27 '22 18:09

tynn


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.

like image 39
Клаус Шварц Avatar answered Sep 27 '22 20:09

Клаус Шварц