Kotlin First Program

Learn via video courses
Topics Covered

Overview

Hello, World! is a simple program that outputs Hello, World! on the screen. It's frequently used to introduce a new programming language because it's a fairly simple program. This lesson explains in detail how to create your first program in Kotlin.

Introduction to Kotlin

Now, before we write our first program in Kotlin, let's know more about what kind of programming language Kotlin is and how it basically works. Kotlin is a multiplatform, statically typed, general-purpose programming language. It supports compilation on the following platforms:

  • JVM (Java Virtual Machine)
  • JS (JavaScript)
  • Native (native binaries for various architectures)

Additionally, it provides transparent platform interoperability thanks to the Kotlin Multiplatform Project (Kotlin MPP) capability.

Kotlin's type system differentiates between nullable and non-nullable types at compile time, ensuring null-safety, and incorporates gradual and flow typing elements to enhance language compatibility and development ease.

Kotlin Architecture and How It Works

Implementing your first program in Kotlin also requires you to really understand in depth how the Kotlin architecture works.

The general structure and organization of a software system are referred to as architecture in the context of programming languages. It includes the design tenets, patterns, and elements needed to build dependable, expandable, and upgradeable applications.

The architecture of any programming language is what is in charge of effectively allocating memory and producing the best results.

architecture of any programming language

Let's understand how Kotlin source code undergoes a series of transformations, starting from the high-level Kotlin code and ending with the generation of machine-specific binaries for a range of hardware architectures facilitated by the Kotlin Native toolchain and LLVM, and enables Kotlin to run on different platforms Starting with the kotlin source code, Kotlin Native stack allows Kotlin code to be compiled for native platforms (non-JVM platforms). It consists of several components:

a. Kotlin Native Computer: This is the specific target hardware or architecture for which we want to compile our Kotlin source code. Examples include PowerPC, RISC-C, ARM, X86, MIPS, and X64. Each of these architectures has its own set of instructions and capabilities.

b. LLVM Intermediate Representation (IR): The Kotlin code is translated into LLVM IR, which is an intermediate language that is platform-independent. It allows for further optimization and transformation before generating machine-specific code.

c. LLVM Compiler: The LLVM compiler takes the LLVM IR code as input and produces machine-specific binaries. These binaries are executables that can run directly on the respective hardware architectures (PowerPC, RISC C-, ARM, X86, MIPS, or X64). The LLVM compiler optimizes the code for each specific architecture, ensuring efficient execution.

Writing Your First Kotlin Program

Let's see how you can start the process of writing your first Kotlin program in IntelliJ IDEA.

In this article, we'll be using the Gradle build system.

While creating applications, we often encounter challenges that others have already tackled and generously shared their solutions online in the form of libraries. These libraries can be incorporated into our apps and customized to suit our specific requirements. To achieve this, we utilize a build.gradle file, where we specify the unique package names and versions of the libraries we wish to implement.

We have the following reasons to choose Gradle:

  1. Kotlin Compatibility: Gradle has excellent support for the Kotlin programming language for building, testing, and running Kotlin code.
  2. Dependency Management: Gradle simplifies dependency management for Kotlin projects. Gradle handles the download and integration of libraries, including Kotlin itself.
  3. Extensibility: Gradle's plugin system allows us to customize the build process to suit our project's needs. There are Kotlin-specific plugins available that make it easy to work with Kotlin-specific tools and frameworks.
  4. Multi-Platform Support: Gradle supports multi-platform projects like Android, JVM, JavaScript, and native (via Kotlin/Native), making it a suitable choice for Kotlin projects targeting different platforms.
  5. Integration: Gradle can be easily integrated into popular integrated development environments (IDEs) like IntelliJ IDEA, Android Studio, and Visual Studio Code.

1. Create a new project

  • Main window -> Select New Project
  • Name your project; let's say it's "greeting".
  • Language -> Kotlin
  • Select the Gradle build system.
  • For the build script, choose the Kotlin language.
  • Select the desired JDK
  • In case you don't have JDK on your computer, download JDK, select Add JDK in the IDE, and specify the path to the JDK home directory
  • Click on create

create a new kotlin project

2. Write some code

  1. In the Project tool window on the left, expand the node named after your project and open the /src/main/kotlin/main.kt file.

project tool window

  1. Write the following code

Explanation:

The main() function serves as the program's entry point. All Kotlin functions begin with the fun keyword, then the function name, a list of parameters, an optional return type, and the function body.

In this instance, the main function's argument is an array of strings, along with return values. The function does not return any value if the unit type is void, as in Java. The third line prints Hello, World! to print the output of the program.

Note: Semicolons are optional in Kotlin, just like in other modern programming languages. Kotlin supports two types of comments, as follows:

  1. Single line comment
  1. Multiple line comment

Running programs in Kotlin

1. Compile and run applications

  1. Compile the application using the Kotlin compiler:

The -d option indicates the output path for generated class files, which may be either a directory or a .jar file. The -include-runtime option makes the resulting .jar file self-contained and runnable by including the Kotlin runtime library in it.

Here, self-contained means that the resulting JAR file will contain not only our Kotlin application code but also the Kotlin runtime library itself, making the JAR file self-contained as it has everything it needs to run the Kotlin code without relying on the presence of a separate Kotlin runtime installation on the target system.

Therefore, this self-contained JAR file can be distributed and executed on different systems without requiring the user to install Kotlin separately (similar to Java bytecodes). It simplifies deployment by bundling the necessary runtime components within the JAR file.

  1. To see all available options, run:
  1. Run the application.

Here, the word kotlinc is the command-line utility for the Kotlin compiler. It's used to compile Kotlin source code files like hello.kt into executable bytecode or JAR files.

2. Compile and run library

We can create the .jar file without including the Kotlin runtime if we're creating a library that will be used by other Kotlin applications

Why are we not including Kotlin runtime? 

If a library is intended to be used in other Kotlin projects, we can choose not to include the Kotlin runtime in our JAR file because the Kotlin standard library is expected to be present in Kotlin projects' classpaths. Not only are we reducing the size of our JAR file, but we're also avoiding potential version conflicts between our library's Kotlin runtime and the runtime used by the application.

Let's understand this command in depth:

  • kotlinc: is the command-line utility for the Kotlin compiler, which is used to invoke the Kotlin compiler from the command line.
  • main.kt: is the name of the Kotlin source code file that we want to compile.
  • -d hello.jar: is an option that specifies the output file for the compiled code, instructing the Kotlin compiler to generate a JAR file named hello.jar as the output. The -d flag is short for destination, and it allows you to specify the name and location of the compiled output file.

So, when this command is run, the Kotlin compiler (kotlinc) compiles the main.kt file and packages the resulting bytecode into a JAR file named hello.jar.

This JAR file can then be executed on a Java Virtual Machine (JVM) or used as a library in other Kotlin projects.

As discussed before, it is crucial to ensure that the Kotlin runtime is included in the classpath whenever our library is employed, as binaries produced using this approach depend on it.

The Kotlin script can also be used to execute binaries created by the Kotlin compiler.

3. Compile and run scripts

Kotlin can also be used as a scripting language. A script is a Kotlin source file .kts with top-level executable code.

Code:

Explanation:

  1. Value to path variable is assigned
  • We're doing this by first checking if the -d flag is present in the command-line arguments using args.contains("-d") wherein args is an array containing the command-line arguments passed to the script.
  • If -d is not found the script assigns the current directory (".") as the path
  • If it's found then the script retrieves the argument immediately following it using args[1 + args.indexOf("-d")] because the command might be something like -d path/to/directory, so the path is the argument that comes after -d.
  1. A File object is created based on the determined path and then the listFiles method is used along with a lambda expression for filtering and retrieving the directories within that path.
  2. The array of file objects representing directories obtained is then iterated upon with the help of safe call operator ?. in order to ensure folders are not null before iteration. It then proceeds on to print the directory's path

To run a script, pass the -script option to the compiler with the corresponding script file:

  • kotlinc: As we've discussed earlier in this article this is used to invoke the Kotlin compiler.
  • -script list_folders.kts: This command specifies that we're using a Kotlin script named list_folders.kts.
  • --: is used to separate the compiler options from the script's arguments, any arguments following it should be treated as script arguments rather than compiler options.
  • -d <path_to_folder_to_inspect>: This is a script argument passed to the list_folders.kts script. It specifies the path to the folder that we want to inspect and list the folders from.

Basically this command is telling the Kotlin compiler to execute the list_folders.kts script and pass the path of the folder we want to inspect as an argument to the script wherein we would access this argument and use it to list the folders within the specified directory.

Summary

  1. Kotlin is a multiplatform, statically typed, general-purpose programming language. It supports compilation to
    • JVM (Java Virtual Machine)
    • JS (JavaScript)
    • Native (native binaries for various architectures)
  2. Self-contained JAR file can be then distributed and executed on different systems without requiring the user to install Kotlin separately
  3. Kotlin's type system distinguishes between nullable and non-nullable types at compile time to provide null-safety, or the absence of runtime problems brought on by the absence of a value
  4. If a library is intended to be used in other Kotlin projects, we can choose not to include the Kotlin runtime in our JAR file because the Kotlin standard library is expected to be present in Kotlin projects' classpaths
  5. Build.gradle file specifies the unique package names and versions of the libraries we wish to implement
  6. Coroutines are lightweight threads that facilitate non-blocking concurrency and are natively supported by Kotlin