“Hello World!”
-
In your editor, create a file named
Hello.kt, containing the following code. Save your file to thetasks/task1_1subdirectory 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
mainas 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
printlnandprint. 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.
-
In a terminal window, cd to the
tasks/task1_1subdirectory of your repository and then compile the program with this command:kotlinc Hello.ktIf this fails, check that you are in the directory containing the
Hello.ktfile, 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). -
Investigate what the compiler has produced. On Linux or macOS, use
ls -lto check directory contents & file creation times, then usefileto query file type. -
Run the compiled program with
kotlin HelloKtBe sure to type this command exactly as shown here!
-
You would need semi-colons if you wanted to put multiple statements on a single line. Kotlin also uses semi-colons in
enumclasses. ↩