Learning a programming language is a daunting experience for many people and not one that most individuals generally choose to undertake. Regardless of the problem domain that you may wish to build solutions for, be it application development, networking, or distributed systems, Kotlin programming is a good choice for the development of systems to achieve the required solutions. In other words, a developer can't go wrong with learning Kotlin.
In this article, you will learn the following:
Kotlin is a strongly-typed, object-oriented language that runs on the Java Virtual Machine (JVM) and can be used to develop applications in numerous problem domains. In addition to running on the JVM, Kotlin can be compiled to JavaScript, and as such, is an equally strong choice for developing client-side web applications. Kotlin can also be compiled directly into native binaries that run on systems without a virtual machine via Kotlin/Native. The Kotlin programming language was primarily developed by JetBrains – a company based in Saint Petersburg, Russia. The developers at JetBrains are the current maintainers of the language. Kotlin was named after Kotlin island – an island near Saint Petersburg.
Kotlin was designed for use in developing industrial-strength software in many domains but has seen the majority of its users come from the Android ecosystem. At the time of writing this post, Kotlin is one of the three languages that have been declared by Google as an official language for Android. Kotlin is syntactically similar to Java. As a matter of fact, it was designed to be a better alternative to Java. As a consequence, there are numerous significant advantages to using Kotlin instead of Java in software development.
In order to develop the Kotlin program, you will first need to install the Java Runtime Environment (JRE) on your computer. The JRE can be downloaded prepackaged along with a Java Development Kit (JDK). For the sake of this installation, we will be using the JDK.
The easiest way to install a JDK on a computer is to utilize one of the JDK installers made available by Oracle (the owners of Java). There are different installers available for all major operating systems. Releases of the JDK can be downloaded from http://www.oracle.com/technetwork/java/javase/downloads/index.html:
Clicking on the JDK download button takes you to a web page where you can download the appropriate JDK for your operating system and CPU architecture. Download a JDK suitable for your computer and continue to the next section:
In order to install the JDK on your computer, check out the necessary installation information from the following sections, based on your operating system.
The JDK can be installed on Windows in four easy steps:
After the JDK installation has concluded, you will need to set the JAVA_HOME environment variable on your computer. To do this:
In order to install the JDK on macOS, perform the following steps:
The JDK will be installed and a confirmation window displayed.
Installation of the JDK on Linux is easy and straightforward using apt-get:
sudo apt-get update
java -version
sudo apt-get install default-jdk
That's it! The JDK will be installed on your computer.
Now that we have the JDK set up and ready for action, we need to install a means to actually compile and run our Kotlin programs.
Kotlin programs can be either compiled directly with the Kotlin command-line compiler or built and run with the Integrated Development Environment (IDE).
The command-line compiler can be installed via Homebrew, SDKMAN!, and MacPorts. Another option for setting up the command-line compiler is by manual installation.
The Kotlin command-line compiler can be installed on macOS in various ways. The two most common methods for its installation on macOS are via Homebrew and MacPorts.
Homebrew is a package manager for the macOS systems. It is used extensively for the installation of packages required for building software projects. To install Homebrew, locate your macOS terminal and run:
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
You will have to wait a few seconds for the download and installation of Homebrew. After installation, check to see whether Homebrew is working properly by running the following command in your terminal:
brew -v
If the current version of Homebrew installed on your computer is printed out in the terminal, Homebrew has been successfully installed on your computer.
After properly installing Homebrew, locate your terminal and execute the following command:
brew install kotlin
Wait for the installation to finish, after which you are ready to compile Kotlin programs with the command-line compiler.
Similar to HomeBrew, MacPorts is a package manager for macOS. Installing MacPorts is easy. It can be installed on a system by:
MacPort versions can be downloaded from https://www.macports.org/install.php.
Once downloaded, locate your terminal and run port install kotlin as the superuser:
sudo port install kotlin
Linux users can easily install the command-line compiler for Kotlin with SDKMAN!
This can be used to install packages on Unix-based systems such as Linux and its various distributions, for example, Fedora and Solaris. SDKMAN! can be installed in three easy steps:
curl -s "https://get.sdkman.io" | bash
source "$HOME/.sdkman/bin/sdkman-init.sh"
sdk version
If the version number of SDKMAN! just installed is printed in your terminal window, the installation was successful.
Now that we have SDKMAN! successfully installed on our system, we can install the command-line compiler by running:
sdk install kotlin
In order to use the Kotlin command-line compilers on Windows:
You can now make use of the Kotlin compiler from your command line.
Now that we have our command-line compiler set up, let's try it out with a simple Kotlin program. Navigate to your home directory and create a new file named Hello.kt. All Kotlin files have a .kt extension appended to the end of the filename.
Open the file you just created in a text editor of your choosing and input the following:
// The following program prints Hello world to the standard system output.
fun main (args: Array<String>) {
println("Hello world!")
}
Save the changes made to the program file. After the changes have been saved, open your terminal window and input the following command:
kotlinc hello.kt -include-runtime -d hello.jar
The preceding command compiles your program into an executable, hello.jar. The -include- runtime flag is used to specify that you want the compiled JAR to be self-contained. By adding this flag to the command, the Kotlin runtime library will be included in your JAR. The -d flag specifies that, in this case, we want the output of the compiler to be called.
Now that we have compiled our first Kotlin program, we need to run it—after all, there's no fun in writing programs if they can't be run later on. Open your terminal, if it's not already open, and navigate to the directory where the JAR was saved to (in this case, the home directory). To run the compiled JAR, perform the following:
java -jar hello.jar
After running the preceding command, you should see Hello world! printed on your display. Congratulations, you have just written your first Kotlin program!
As previously stated, Kotlin can be used to write scripts. Scripts are programs that are written for specific runtime environments for the common purpose of automating the execution of tasks. In Kotlin, scripts have the .kts file extension appended to the file name.
Writing a Kotlin script is similar to writing a Kotlin program. In fact, a script written in Kotlin is exactly like a regular Kotlin program! The only significant difference between a Kotlin script and regular Kotlin program is the absence of a main function.
Create a file in a directory of your choosing and name it NumberSum.kts. Open the file and input the following program:
val x: Int = 1
val y: Int = 2
val z: Int = x + y
println(z)
As you've most likely guessed, the preceding script will print the sum of 1 and 2 to the standard system output. Save the changes to the file and run the script:
kotlinc -script NumberSum.kts
REPL is an acronym that stands for Read–Eval–Print Loop. An REPL is an interactive shell environment in which programs can be executed with immediate results given. The interactive shell environment can be invoked by running the kotlinc command without any arguments.
If the REPL is successfully started, a welcome message will be printed in your terminal followed by >>> on the next line, alerting us that the REPL is awaiting input. Now you can type in code within the terminal, as you would in any text editor, and get immediate feedback from the REPL. This is demonstrated in the following screenshot:
In the preceding screenshot, the 1 and 2 integers are assigned to x and y, respectively. The sum of x and y is stored in a new z variable and the value held by z is printed to the display with the print() function.
Writing programs with the command line has its uses, but in most cases, it is better to use software built specifically for the purpose of empowering developers to write programs. This is especially true in cases where a large project is being worked on.
An IDE is a computer application that hosts a collection of tools and utilities for computer programmers for software development. There are a number of IDEs that can be used for Kotlin development. Out of these IDEs, the one with the most comprehensive set of features for the purpose of developing Kotlin applications is IntelliJ IDEA. As IntelliJ IDEA is built by the creators of Kotlin, there are numerous advantages in using it over other IDEs, such as an unparalleled feature set of tools for writing Kotlin programs, as well as timely updates that cater to the newest advancements and additions to the Kotlin programming language.
IntelliJ IDEA can be downloaded for Windows, macOS, and Linux directly from JetBrains' website: https://www.jetbrains.com/idea/download. On the web page, you are presented with two available editions for download: a paid Ultimate edition and a free Community edition. The Community edition is sufficient if you wish to run the programs in this chapter. Select the edition you wish to download:
Once the download is complete, double-click on the downloaded file and install it on your operating system as you would any program.
The process of setting up a Kotlin project with IntelliJ is straightforward:
Your project will be created and you will be presented with the IDE window:
To the left of the window, you will immediately see the project view. This view shows the logical structure of your project files.
Two folders are present. These are:
Now that the project is set up, we will write a simple program. Add a file named hello.kt to the source folder (right-click the src folder, select New | Kotlin File/Class, and name the file hello). Copy and paste the following code into the file:
fun main(args: Array<String>) { println("Hello world!") }
To run the program, click the Kotlin logo adjacent to the main function and select Run HelloKt:
The project will be built and run, after which, Hello world! will be printed to the standard system output.
Advantages of Kotlin
As previously discussed, Kotlin was designed to be a better Java, and as such, there are a number of advantages to using Kotlin over Java:
To summarize, we introduced Kotlin and explored the fundamentals. In the process, we learned how to install, write and run Kotlin scripts on a computer and how to use the REPL and IDE.
This tutorial is an excerpt from the book, Kotlin Programming By Example, written by Iyanu Adelekan. This book will help you enhance your Kotlin programming skills by building real-world applications.
Build your first Android app with Kotlin
How to convert Java code into Kotlin