Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

“Hello World!”

  1. In your editor, create a file named Hello.kt, containing the following code. Save your file to the tasks/task1_1 subdirectory of your repository.

    Tip

    You can use the ‘Copy to Clipboard’ button that appears in the top-right of the code panel to help with this, but we strongly recommend that you actually type in the code, as this will help you acclimatize more rapidly to Kotlin features and syntax.

    fun main() {
        println("Hello World!")
    }
    

    Notice that functions are defined using fun, and that the start of the function body is marked by a left brace, as in C.

    Kotlin recognizes a function named main as the entry point for a program, just like C does.

    Printing to the console is similar to Python, except that Kotlin has two functions for this, named println and print. The former prints a newline at the end of the given string, whereas the latter does not.

    Note also that there is no semi-colon at the end of the statement! Kotlin hardly ever requires them1.

    A right brace marks the end of the function body. Like C, Kotlin uses pairs of braces to define blocks, rather than following Python’s approach of using indentation.

  2. In a terminal window, cd to the tasks/task1_1 subdirectory of your repository and then compile the program with this command:

    kotlinc Hello.kt
    

    Troubleshooting

    If this fails, check that you are in the directory containing the Hello.kt file, and make sure that the Kotlin command line compiler is installed properly (see the information provided on working in a Codespace and working locally for help with this).

  3. Investigate what the compiler has produced. On Linux or macOS, use ls -l to check directory contents & file creation times, then use file to query file type.

  4. Run the compiled program with

    kotlin HelloKt
    

    Be sure to type this command exactly as shown here!


  1. You would need semi-colons if you wanted to put multiple statements on a single line. Kotlin also uses semi-colons in enum classes.