0
0
KotlinHow-ToBeginner · 3 min read

How to Run Kotlin from Command Line: Simple Steps

To run Kotlin from the command line, first write your Kotlin code in a .kt file, then compile it using kotlinc filename.kt -include-runtime -d filename.jar. Finally, run the compiled program with java -jar filename.jar.
📐

Syntax

Here is the basic syntax to compile and run Kotlin code from the command line:

  • kotlinc filename.kt -include-runtime -d filename.jar: Compiles the Kotlin file into a runnable JAR file.
  • java -jar filename.jar: Runs the compiled Kotlin program.

Explanation: kotlinc is the Kotlin compiler command. -include-runtime adds the Kotlin runtime to the JAR so it can run standalone. -d specifies the output file name.

bash
kotlinc HelloWorld.kt -include-runtime -d HelloWorld.jar
java -jar HelloWorld.jar
💻

Example

This example shows a simple Kotlin program saved in HelloWorld.kt. It prints a greeting message to the console.

kotlin
fun main() {
    println("Hello, Kotlin from command line!")
}
Output
Hello, Kotlin from command line!
⚠️

Common Pitfalls

Common mistakes when running Kotlin from the command line include:

  • Forgetting to include -include-runtime when compiling, which causes runtime errors.
  • Not using java -jar to run the compiled JAR file.
  • Trying to run kotlinc output directly without packaging it as a JAR.

Always compile with runtime included and run with java -jar.

bash
Wrong way:
kotlinc HelloWorld.kt -d HelloWorld.jar
java HelloWorld.jar

Right way:
kotlinc HelloWorld.kt -include-runtime -d HelloWorld.jar
java -jar HelloWorld.jar
📊

Quick Reference

CommandDescription
kotlinc filename.kt -include-runtime -d filename.jarCompile Kotlin file into runnable JAR
java -jar filename.jarRun the compiled Kotlin program
kotlinc filename.ktCompile Kotlin file to class files (no runtime included)
kotlin filenameRun Kotlin script directly (if installed)

Key Takeaways

Use kotlinc with -include-runtime to compile Kotlin code into a runnable JAR.
Run the compiled Kotlin program using java -jar filename.jar.
Always include the Kotlin runtime in the JAR to avoid runtime errors.
You can also run Kotlin scripts directly with the kotlin command if installed.
Check your file names and commands carefully to avoid common mistakes.