This article is from Kotlin’s Definitive Guide to Programming

In this chapter, you will learn to develop your first Kotlin application using IntelliJ IDEA. This will familiarize you with the development environment, create new Kotlin projects, write and run Kotlin code, and view the output. This chapter creates a sandbox project that you can walk through code to learn and understand the various new concepts in the book.

1.1 Installing IntelliJ IDEA

IntelliJ IDEA is a Set of Kotlin integrated development environment. JetBrains created the Kotlin language and built the development tools. Before you start to learn, please visit JetBrains website www.jetbrains.com/idea/downlo… Download the IntelliJ IDEA community development version software (see Figure 1-1).

Figure 1-1 Downloading IntelliJ IDEA community development edition software

After the download is complete, please refer to www.jetbrains.com/help/idea/i… Complete the installation and configuration of IntelliJ IDEA development tool on the corresponding platform.

IntelliJ IDEA, short for IntelliJ, helps developers write well-styled Kotlin code. With its built-in tools, the entire development process of running, debugging, reviewing, and refactoring code is seamless and seamless. For this reason, we recommend using IntelliJ for Kotlin development. To learn more about why you should use IntelliJ for Kotlin development, read Section 1.4.

1.2 The first Kotlin project

Congratulations, now that you have the Kotlin language and a powerful development environment, there is only one thing left to do: learn to use the Kotlin language fluently. As our first hands-on task, let’s create a Kotlin project.

Start the IntelliJ. As shown in Figure 1-2, you can see the welcome interface of IntelliJ IDEA.

Figure 1-2 Welcome page

(IntelliJ will open the previous project directly unless it is installed for the first time. To return to the welcome screen, select File → Close Project to Close the Project.

Click the Create New Project option and you will see the Create New Project dialog shown in Figure 1-3.

Figure 1-3 Create new project dialog box

In the Create new Project dialog box, select the Kotlin option on the left, and then select the Kotlin/JVM option that appears on the right, as shown in Figure 1-4.

Figure 1-4 Creating a Kotlin/JVM project

In addition to Kotlin, IntelliJ supports other programming languages such as Java, Python, Scala, and Groovy. Selecting Kotlin/JVM tells IntelliJ that you want to program in Kotlin. More specifically, it means writing Kotlin code for and running on the Java virtual machine. Kotlin, by the way, has another advantage: the built-in toolchain allows you to write Kotlin code that runs on different operating systems and platforms.

From now on, when it comes to the Java Virtual machine, this book will refer instead to the JVM commonly used by the Java development community. More on JVM orientation in Section 1.5.)

Click the Next button to continue. You should see the new project Settings screen, as shown in Figure 1-5. Enter “Sandbox” as the project name and IntelliJ will automatically give you the default project path. If necessary, click on the right… Button to customize the project path. Click Java 1.8 from the Project SDK drop down box, so the new Project is associated with JDK 8.

Figure 1-5 Naming the new project

Why, you might ask, do you need a JDK to write Kotlin programs? The answer is that in order to translate Kotlin code into bytecode (more on that later), IntelliJ needs the JDK to provide the JVM and Java tools. In theory, JDK 6 and later versions work, but experience suggests that at the time of writing, JDK 8 works better.

If you don’t see Java 1.8 in the Project SDK drop-down box, you haven’t installed JDK 8 yet. Before attempting to continue learning, please visit www.oracle.com/technetwork. To complete the installation, download the installation package for the corresponding platform, and restart IntelliJ to make it take effect. Finally, follow the previous steps to create the new project from scratch.

Without further ado, confirm the new project Settings as shown in Figure 1-5, and click the Finish button.

As shown in Figure 1-6, IntelliJ then creates a new project named Sandbox and displays it in the default two-panel view. Reflected on the hard disk, IntelliJ creates a folder, a series of subfolders, and corresponding project files in the path specified for the project.

Figure 1-6 Default dual-panel view

In Figure 1-6, the project tool window is displayed on the left panel. The right panel is now empty. As you will see in a moment, an editor window is displayed for you to view and edit the Kotlin code file. Take a look at the project Tools window on the left. Click the expansion arrow to the left of the project name Sandbox to display the files contained in the project, as shown in Figure 1-7.

Figure 1-7 Project view

In IntelliJ, the project contains all the source code for our application, as well as the associated dependencies and configuration information. Projects can be divided into one or more modules that are similar to subprojects. A new project contains one module by default, which is enough for a simple Kotlin project.

As shown in Figure 1-7, the sandbox.iml file contains the configuration information for the project module. The.idea folder holds the setup files for the entire project, as well as Settings related to the user’s interaction with the project in the IDE (for example, which file is currently open in the editor). The above files are automatically generated by the system, so don’t worry about them now.

The External Libraries TAB contains information about the Libraries that the project depends on. Click to expand the item and you can see that IntelliJ has automatically added Java 1.8 and the KotlinJavaRuntime dependency libraries to the project.

(to learn more knowledge about IntelliJ project structure, please visit the JetBrains document url: www.jetbrains.org/intellij/sd… ).

The SRC folder is used to store all the Kotlin code files created for the Sandbox project. Ok, it’s time to create and edit the first Kotlin code file.

1.2.1 Creating the first Kotlin file

In the project tools window, right – click the SRC folder. As shown in Figure 1-8, select The New and Kotlin File/Class menu items in sequence.

Figure 1-8 Creating a Kotlin file

In the New Kotlin File/Class dialog box, type the File Name “Hello” at Name, leaving the File option at Kind unchanged (see Figure 1-9).

Figure 1-9 Naming the Kotlin file

Click the OK button to confirm. As shown in Figure 1-10, IntelliJ then creates a new project file, SRC/hello. kt, and opens the file in the editor of the IntelliJ window on the right. We know that the.java suffix is used for Java files, the.py suffix is used for Python files, and the.kt suffix means that the new file holds Kotlin code.

Figure 1-10 Hello.kt empty file in the editor

Now you are ready to write Kotlin code. In the Hello.kt editor, go ahead and enter the code shown in Listing 1-1. (Note that all code in this book that requires reader input is shown in bold.)

Listing 1-1 “Hello,World!” Kotlin Language Version (Hello.kt)

fun main(args: Array<String>) {
    println("Hello, world!" )
}

Don’t quite understand the code you just entered? Don’t worry, by the end of this book you’ll be able to read and write Kotlin code naturally and fluently. For now, you just have a rough idea of the output “Hello,World!” A string will do.

The code in Listing 1-1 defines a new main function. A function is really a set of code instructions that can be run later. We’ll learn more about defining and using functions in Chapter 4.

The main function has special meaning for the Kotlin language. It is the place where the application starts, also known as the application entry point. For a Sandbox or any application to run, such entry points must be defined. All applications written in this book start with the main function.

The main function in the above code contains only one instruction (also known as a statement) : println(“Hello, world! ). Println () is also a function, built into the Kotlin library. Once the Sandbox application runs, println(“Hello, world! ), and IntelliJ prints Hello, world! In parentheses on the screen. A string.

1.2.2 Running the Kotlin file

As shown in Figure 1-11, once you have entered the code in Listing 1-1, a green run button appears to the left of the first line of code. (If the green run button does not appear, or a red wavy line is marked below the hello. kt file name or some code, it indicates that the code is wrong. Please check and modify the code carefully against Listing 1-1. Also, it’s ok to see Kotlin’s red and blue K logo, which is the equivalent of running the button.)

Figure 1-11 Run button

If the code is correct, Hello, world! The application is ready to run. Click the Run button and select the Run ‘HelloKt’ menu item, as shown in Figure 1-12. This is the equivalent of telling IntelliJ that you want to see the app work.

Figure 1-12 Running the hello. kt file

When the application runs, IntelliJ executes the code in curly braces ({}) line by line, while displaying two new tool Windows at the bottom of the IDE interface, as shown in Figure 1-13.

Figure 1-13 Run and event log tool window

In Figure 1-13, on the left is the run tools window, also known as the console (as it will be called later). The console displays various information generated by IntelliJ as it executes the application, as well as the output of the application itself. In this case, you’ll see the console say Hello, World! String, you will also see the statement that indicates successful execution of the application: Process finished with exit code 0. This statement appears at the end of the console output. As long as you know, this information will not be included in subsequent screenshots of this book.

MacOS users may see red error text indicating that there is a problem with JavaLauncherHelper, as shown in Figure 1-13. Don’t worry. This is a side effect of the way the Java runtime environment is installed on macOS. It takes some work to remove it, but the problem doesn’t matter, so you can just ignore it and continue.)

In Figure 1-13, is on the rightEvent logging tool window. This window displays information about the work that IntelliJ does for the application. Obviously, the console is where we care, so the event log window won’t be mentioned in the future. (Likewise, you don’t care if the event log window is open while the application is running.) To close the event logging window, click the Hide button in the upper right cornerCan.

Compile and run the Kotlin code

Print Hello, World! From the Run ‘HelloKt’ menu item to the console. It only takes a short time, but there’s a lot going on in the background.

First, IntelliJ compiles the Kotlin code using the Kotlinc-JVM compiler. Specifically, this translates Kotlin code into the JVM language: bytecode. If there are problems during the conversion, kotlinc-JVM will report an error and give a troubleshooting message. If all goes well, IntelliJ will go into execution.

During the execution phase, the bytecode generated by kotlinc-JVM is executed on the JVM. The console then prints program output, for example, calling the println() function prints the text passed into it as the JVM executes instructions one by one.

After the bytecode instruction completes execution, the JVM terminates. IntelliJ displays the termination status on the console, telling the user that the execution completed successfully or that there was an error and assigning error codes.

Chapter 2 will delve deeper into bytecode, but it’s important to note that you can read this book without fully understanding Kotlin’s compilation process.

1.3 Kotlin REPL

Just like taking a piece of paper and working through a calculation step by step, sometimes you might want to test a small piece of Kotlin code to see how it works. This is very useful when learning Kotlin. Fortunately, IntelliJ provides just such a tool for quickly testing code without creating files. The tool is called Kotlin REPL. I’ll explain what REPL means later, but let’s open it up and see what you can do with it.

As shown in Figure 1-14, in IntelliJ, choose Tools → Kotlin → Kotlin REPL to open the Kotlin REPL tool window.

Figure 1-14 Opening the Kotlin REPL tool window

As shown in Figure 1-15, IntelliJ displays the REPL window at the bottom.

Figure 1-15 Kotlin REPL tool window

You can type code in there, just like you would with a code editor, but with one difference: the REPL doesn’t compile the entire project, it gives you the results immediately.

Enter the code shown in Listing 1-2 in the REPL.

Listing 1-2 “Hello, Kotlin!” (REPL)

println("Hello, Kotlin!" )

After typing, press the command-return (Ctrl-return) key combination to execute the code in the REPL. As shown in Figure 1-16, you’ll soon see Hello, Kotlin! Output the result.

Figure 1-16 Executing the code

REPL is an acronym for read, evaluate, print, and loop. Here’s how it works: Type a piece of code at the prompt, and then click the green run button to the left of the REPL or command-Return (Ctrl-Return) to commit. The REPL reads the code, evaluates the code (runs the code), and outputs the result or side effect result. When it finishes, the REPL cedes control and the cycle begins again.

Kotlin’s journey has begun! You’ve learned a lot in this chapter, laying the groundwork for further mastery of Kotlin programming. In the next chapter, you’ll explore the details of the Kotlin language and learn how to use variables, constants, and various data types.

1.4 In-depth study: Why IntelliJ

Any text editor can be used to write Kotlin code, but we recommend using IntelliJ, especially when learning the language. Just as it was easier to write regular text with the spelling and grammar checking features of word processors, IntelliJ made it easier to write regular Kotlin code. This is mainly reflected in the following aspects.

  • You can write syntactically and semantically correct code with syntax highlighting, content hints, and code auto-completion.
  • With breakpoint debugging and real-time code stepping at application runtime, you can debug code as you run.
  • You can refactor existing code with quick refactoring commands (such as rename, export constants) and clean indentation and blank line code formatting capabilities.

And because Both Kotlin and IntelliJ are from JetBrains, the integration design between them is more thorough and provides a pleasant development experience for users. In addition, Android Studio is built on IntelliJ, so shortcuts and tools learned while using IntelliJ can be used directly.

1.5 In-depth Learning: For the JVM

The JVM is essentially software that knows how to execute bytecode instructions. “Jvm-oriented” means compiling or translating Kotlin code into Java bytecode for running on the JVM, as shown in Figure 1-17.

Figure 1-17 Compilation and execution process

Both Windows and macOS platforms have their own set of instructions. The JVM Bridges bytecodes with different hardware and software platforms, reading bytecodes and invoking platform-specific instructions that match them. Obviously, there are different versions of the JVM for different hardware and software platforms. This allows Kotlin developers to write platform-independent code that can be written once, compiled into bytecode and executed on different devices, regardless of the system platform.

Since it can be translated into bytecode that the JVM can execute, Kotlin is the JVM language. Java is best known as the first JVM language. In later languages, such as Scala and Kotlin, developers have eliminated some of the shortcomings of “older” Java by playing to its strengths and avoiding its weaknesses.

Kotlin is not limited to the JVM, however. As this book is written, Kotlin can compile to JavaScript, even out of the virtual machine layer, into native binaries that run on Windows, Linux, and macOS platforms.

1.6 Challenge Exercise: Investigate arithmetic operators in Kotlin using REPL

Many chapters of the book have challenging exercises at the end. Please complete them independently to deepen your understanding of the Kotlin language and gain more experience.

Use REPL to explore how the +, -, *, /, and % arithmetic operators in Kotlin work. For example, in REPL, try typing (9+12)*2. Did the results meet expectations?

Also want to further study, you can see kotlinlang.org/api/latest/… The mathematical functions listed in Kotlin’s standard library are rehearsed in REPL. For example, try minOf (94, -99) to find the minimum.