Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compile mixed Kotlin and Java code from the command line

Tags:

kotlin

I'd like to start adding some Kotlin to my Java project. To do that I need to be able to compile both Java and Kotlin files from the command line, which is fine apart from when files of different types depend on each other e.g. A.java depends on B.kt which in turn depends on C.java.

Is there any way to do this without using Gradle, Maven etc?

Edited to clarify thanks @Nikita for pointing out it is not clear that I want both java and Kotlin files in the same source tree

like image 301
Ben Halton Avatar asked Nov 21 '15 13:11

Ben Halton


People also ask

How do I combine Kotlin and Java?

Control + Alt + shift + k, by this shortcut you can migrate your java code as kotlin.

Can you compile Kotlin to Java?

The Kotlin compiler for JVM compiles Kotlin source files into Java class files. The command-line tools for Kotlin to JVM compilation are kotlinc and kotlinc-jvm . You can also use them for executing Kotlin script files.

Does Kotlin use Javac?

No, kotlinc compiles only Kotlin files ( . kt ). A mixed-language project requires combining both kotlinc and javac .

Can you use Java and Kotlin together in Android Studio?

Adding Java source code to an existing Kotlin project If you already have the Java classes, you can just copy them to the project directories. You can now consume the Java class from Kotlin or vice versa without any further actions. lets you call it from Kotlin like any other type in Kotlin.


2 Answers

To achieve this, you will need to run two steps.

  1. Run kotlinc targeting *.kt files. Add all required java sources on classpath. Note the destination location.
  2. Run javac targeting *.java files. Add *.class files created by step 1 to classpath.

Result is a combination of *.class files from both steps.

Here is a documetation on Kotlin compiler

like image 147
Nikita Skvortsov Avatar answered Sep 30 '22 09:09

Nikita Skvortsov


Remember to compile Kotlin first, then compile Java with kotlin-build-classpath from first step.

simple like this:

1. kotlinc ./src/* -d ./buildTmp
2. javac ./src/**.java -d ./buildTmp -classpath ./buildTmp
like image 38
fengma Avatar answered Sep 30 '22 09:09

fengma