Kotlin is a modern, statically typed programming language that runs on the Java Virtual Machine (JVM). While many developers use powerful Integrated Development Environments (IDEs) like IntelliJ IDEA to write Kotlin code, you might prefer to work in a terminal environment. This guide provides a step-by-step process for installing and setting up Kotlin on the command line.
Step 1: Install Java
Since Kotlin runs on the JVM, you need to have Java installed on your system. If you haven't installed Java yet, you can download it from the official Oracle Java downloads page or use a package manager like Homebrew for macOS, apt for Ubuntu, or another similar tool depending on your operating system.
# macOS
brew install openjdk@11
# Ubuntu
sudo apt update
sudo apt install openjdk-11-jdk
# Windows
# Download the installer from Oracle's website and follow the setup instructions
Step 2: Verify Java Installation
Once Java is installed, verify the installation with the following command:
java -versionThis should display the installed version of Java.
Step 3: Install Kotlin
With Java set up, you can now install Kotlin. The official way to run Kotlin from the command line is by using the Kotlin compiler. You can obtain this through the Kotlin binary distribution or SDKMAN!
# Using SDKMAN!
curl -s "https://get.sdkman.io" | bash
source "$HOME/.sdkman/bin/sdkman-init.sh"
sdk install kotlinYou can also manually download the Kotlin compiler from the Kotlin website, and move it to a directory included in your system's PATH.
Step 4: Verify Kotlin Installation
After installing the Kotlin compiler, verify the installation:
kotlinc -versionThis command should output the version of Kotlin installed on your system.
Step 5: Write Your First Kotlin Program
Create a new directory for your Kotlin files, and inside that directory, create a new file named HelloWorld.kt:
mkdir kotlin-sample
cd kotlin-sample
echo 'fun main() { println("Hello, World!") }' > HelloWorld.ktStep 6: Compile and Run Kotlin Code
To compile your Kotlin code, use the kotlinc command:
kotlinc HelloWorld.kt -include-runtime -d HelloWorld.jarThis command compiles HelloWorld.kt and outputs an executable JAR file named HelloWorld.jar.
Run the compiled Kotlin program with the following command:
java -jar HelloWorld.jarIf everything is set up correctly, you should see the output Hello, World!.
Conclusion
That's it! You've successfully set up Kotlin on your command line. You can now write, compile, and execute Kotlin programs without the need for a full-fledged IDE. This is a great setup for learning and practicing Kotlin in a lightweight development environment. Happy coding!