How to Run Kotlin Program: Simple Steps for Beginners
To run a Kotlin program, write your code in a file with
.kt extension, then compile it using kotlinc and run the generated class with kotlin command. Alternatively, use an IDE like IntelliJ IDEA to write and run Kotlin code with one click.Syntax
A basic Kotlin program starts with a fun main() function which is the entry point. Inside main, you write code to execute. Use println() to print output to the console.
Example syntax:
fun main() { }: Defines the main function.println("text"): Prints text to the screen.
kotlin
fun main() {
println("Hello, Kotlin!")
}Example
This example shows a complete Kotlin program that prints a greeting message. You can save it as Hello.kt, compile, and run it.
kotlin
fun main() {
println("Hello, Kotlin!")
}Output
Hello, Kotlin!
Common Pitfalls
Common mistakes include:
- Not having a
mainfunction, so the program has no starting point. - Saving the file with the wrong extension (must be
.kt). - Trying to run Kotlin code without compiling first.
- Using Java commands instead of Kotlin commands to run the program.
Always compile with kotlinc and run with kotlin.
kotlin
/* Wrong: Trying to run without main function */ // This will not run /* Right: Include main function */ fun main() { println("Runs correctly") }
Quick Reference
| Command | Description |
|---|---|
| kotlinc Hello.kt -include-runtime -d Hello.jar | Compile Kotlin file to a runnable jar |
| kotlin -classpath Hello.jar HelloKt | Run compiled Kotlin program (class name without .kt) |
| Using IntelliJ IDEA | Write code and click Run button to compile and run automatically |
Key Takeaways
Write Kotlin code inside a main() function to run it.
Save files with .kt extension and compile using kotlinc.
Run compiled code using the kotlin command or an IDE.
Common errors come from missing main or wrong file extension.
IDEs like IntelliJ simplify running Kotlin programs with one click.