MewX MewX - 1 year ago 174
Java Question

How to use with `java` command with `kotlin-compiler.jar` to compile Kotlin source codes?

I am now limited to use

command to compile a Kotlin source file.

So after some attempts, I found a
file in the
folder in

Then I tried to write a
file in

public fun main(args: Array<String>) {

And then, I executed the command
java -jar kotlin-compiler.jar Hello.kt
which worked and generated a class file

As a result I executed the command
java -cp ".:kotlin-runtime.jar" HelloKt
, and it also worked:

[xxxxxxx@uss lib]$ java -cp ".:kotlin-runtime.jar" HelloKt

But, for a more complicated source file:


class AimToTen() {
fun need(marks: Array<Int>): Int {
// multiply 10 first
for (idx: Int in marks.indices) marks[idx] *= 10

val result: Int = 190 * marks.size - 2 * marks.sum();
return when {
result < 0 -> 0
result % 10 != 0 -> result / 10 + 1
else -> result / 10;

I tried to execute
java -jar kotlin-compiler.jar AimToTen.kt
, but some functions missed(?):

[xxxxxxx@uss intro1]$ java -jar kotlin-compiler.jar AimToTen.kt
AimToTen.kt:4:32: error: unresolved reference: indices
for (idx: Int in marks.indices) marks[idx] *= 10
AimToTen.kt:10:56: error: unresolved reference: sum
val result: Int = 190 * marks.size - 2 * marks.sum();

So I tried again:

[xxxxxxx@uss intro1]$ java -jar kotlin-compiler.jar
Welcome to Kotlin version 1.0.3 (JRE 1.8.0_65-b17)
Type :help for help, :quit for quit
>>> println(123)
error: unresolved reference: println

>>> var test: IntArray = intArrayOf(1, 2)
>>> test

Also, in other folder, the
cannot be compiled even if I copied all the
files in the same folder.

Ehh, I do appreciate if you can help me with this issue! I want to compile this file with
command, without any absolute paths.

P.S. Using
kotlinc AimToTen.kt

Answer Source

As stated in the docs, the line to compile a Kotlin file is

$ kotlinc hello.kt -include-runtime -d hello.jar

BTW, if you are trying to learn/try out Kotlin in command line (which you should not!), you may consider

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download