Section 1.10 Running a Kotlin program
Up to this point, we have been doing all of our work via demonstrations shown in this book. At some point, we will have to write a complete Kotlin program that we can run from an Integrated Development Environment (IDE) or the command line.
Subsection 1.10.1 Basic Program and File Structure
Hereβs the minimal prototypical Kotlin program:
Letβs go through this line by line.
Line 1: Every program that you want to run must have a function named
main; the operating system will start running your program by calling this method.
Line 2: The function body, which, in this case, consists of a single statement that prints the words
Kotlin works!. This function prints its argument followed by a newlineβln stands for line.
When you save this program, you can use any filename you wish, though it must end with the extension
.kt. For example, we can save this as ExampleProgram.kt.
Subsection 1.10.2 Compiling and Executing the Program
Most Integrated Development Environments are set up so that you can compile and run your Java programs with the click of a button or a menu choice. It is also possible to run a Kotlin program from the command line. Here is an example of running the preceding program from a Linux shell where the
$ is the command line input prompt:
$ kotlinc ExampleProgram.kt $ ls ExampleProgramKt.class ExampleProgram.kt $ kotlin ExampleProgramKt Java works!
The
kotlinc command invokes the Kotlin compiler. It translates the source code into bytecode, a form which the runtime system can execute. This bytecode file is given almost the same name as the original file, but it adds Kt to the main part of the filename, and the extension is .class. So in this case, after compiling, we have a new file named ExampleProgramKt.class. Since there are no errors in the program, there is no output shown on the screen after running kotlinc (βno news is good newsβ).
The
ls command lists the files in the current directory; you donβt need to do this command, but itβs here to show you that, after compiling, you have two files: ExampleProgramKt.class (the bytecode) and ExampleProgram.kt (the source code).
The
kotlin command runs the program. You give it the main part of the name of the compiled bytecode file (in this case, ExampleProgramKt).
You have attempted of activities on this page.

