Write your first Kotlin program

In this codelab, you are going to write your first program in the Kotlin language using an interactive editor that you can run from your browser.

You can think of a program[LINK] as a series of instructions for the system to perform some action. For example, you could write a program that creates a birthday card. In that program, you could write an instruction to print congratulatory text or calculate someone's age from their birth year.

Just like you use human language to communicate with another person, you use a programming language to communicate with the operating system of your computer. Fortunately, programming languages are less complex than human languages and quite logical!

Android apps are written in the Kotlin programming language. Kotlin is a modern language created to help developers write code efficiently and with as few errors as possible.

Learning to create an app and learning the basics of programming at the same time will be challenging, so we are going to start you off with a bit of programming before getting into app creation. Becoming comfortable with some programming basics first is not only an important step towards creating apps, it is also going to make it easier to create your first app later in this course.

Code editors are tools that help you write code, in the same way a word processor (like Google Docs) helps you create text documents. In this codelab, you are using an interactive Kotlin editor within your browser. This means that you do not have to install any software to take your first step towards app development.

Prerequisites

  • Use interactive websites in your web browser.

What you'll learn

  • How to create, change, understand, and run a minimal Kotlin program that displays a message.

What you'll build

  • A program in the Kotlin programming language that displays a message when you run it.

What you need

  • A computer with a modern web browser, such as the latest version of Chrome.
  • Internet access on your computer.

In this task, you will use an editor on a website to start programming in the Kotlin language right away.

Use an interactive code editor

Instead of installing software on your computer, you can use a web-based tool to create your first program.

  1. In your browser, open https://try.kotlinlang.org/. This opens a browser-based programming tool.
  2. You should see a page similar to the screenshot below, with a list of files on the left, and an editor to the right. You may also see a black box in the bottom right corner with cookie policy information.

Warning: If you are not OK with the cookie policy of this site, do not proceed.

  1. Click on the X in the top left corner of the black popup box to close it.
  1. Follow the annotated screenshot below as a reference to orient yourself with this editor.

  • (1) Learn, Community, and Try online tabs at the top. Click the Try online tab, if it's not already selected.
  • (2) File explorer in the leftmost pane. Every folder in this list contains a small, standalone example for learning Kotlin.
  • (3) The editor in the right pane is where you will do most of your work in writing code.

This web-based code editor has many other features, but these are the ones you need to know to get started.

Open the sample code

  1. In the file explorer, if it's not already selected, select Examples > Hello, world! > Simplest version > SimplestVersion.kt (1 in the screenshot below).
  2. In the file name SimplestVersion.kt, notice the .kt file extension (see 1 in the screenshot below). Just like images have a .jpg or .png extension, and PDFs have a .pdf extension, all Kotlin files must have the .kt extension.
  3. Notice the code in the editor (2 in the screenshot below). Some of the code is highlighted. This is the code you will be working with.

This is the highlighted program code in the editor:

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

Run the program code

Running a program that you created is not much different than running a program such as a word processor on your computer. The difference is that when you run a program to accomplish a task, or play a game, you primarily care about what the program can do for you, and you don't concern yourself with the code that makes it work. When you are programming, you get to see and work with the actual code that makes the magic happen.

Let's see what this program does!

  1. In the editor, in the top-right corner, find the green triangle and click it to run the program.

  1. If necessary, scroll down on the page until you see the bottom of the editor to see the pane at the bottom (1 in the screenshot below).

  1. Click on the Console tab. The Console is a place to which programs can print text output.

  1. Notice Hello, world! printed in the Console pane, like in the screenshot above. So now you know what this program does: It prints, or outputs, a hello world message into the Console window.
  2. Observe that above the printed Hello, world! is a message Compilation complete successfully. Compilation is a process that translates the Kotlin program code into a form that the system can run. If compilation completes successfully, there are no errors in the program that would keep it from running.

Parts of a program

Now that you've seen what this program does, take your first look at how it does it.

  1. Look at the program in the editor.
  2. Notice how this code has two distinct sections.

Top part of the program:

/**
 * We declare a package-level function main which returns Unit and takes
 * an Array of strings as a parameter. Note that semicolons are optional.
 */

In the code snippet above, you can see text inside these symbols: /* and */.

This means it is a comment, that is, a message with information for other developers. When you run the program, this comment is ignored by the system. For now, you can ignore this comment, too! You will learn more about comments in a later codelab.

Bottom part of the program:

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

These three lines of code are the actual program that runs and prints the message.

Change the Hello World code

Let's change the program to make it do something a little different.

  1. Change the "Hello, world!" text to say "Happy Birthday!".
  2. Run your program by clicking the green run button at the top right.
  3. In the Console, you should now see Happy Birthday! printed, as shown in the screenshot below.

How does it work?

How is this done? This seems like a lot of code to just to print something!

Well, if you wanted a friend to write "Hello, world!" on a piece of paper, there is a lot of implied information. If you just tell them, "Write 'Hello world!' on this piece of paper", they are going to make assumptions about the information you left out. For example, they are going to assume they need to use a pen, and that you want them to write it using letters! The computer does not make these assumptions, so you have to give precise instructions that include every step.

Just like the English language has structure, so does a programming language. If you've ever learned another language, you know the challenge of learning the grammar, the spelling, perhaps a new alphabet of symbols, and the vocabulary. Learning to program has similar challenges, but fortunately, it is less complex and a lot more logical than learning, for example English.

Understand the parts of the program

Now, take a look at the code. Each piece of this program serves a specific purpose, and you need all the pieces in order to be able to run the program. Let's start with the first word.

fun
  • fun is a word in the Kotlin programming language. fun stands for function. A function is a section of a program that performs a specific task.
fun main
  • main is the name of this function. Functions have names, so they can be distinguished from each other. This function is called main, because it is the first, or main, function that is called when you run the program. Every Kotlin program needs a function named main.
fun main()
  • The function name is always followed by () two parentheses.
fun main(args: Array<String>)
  • Inside the parentheses, you can put information for the function to use. This input to the function is called "arguments" or args for short. You will learn more about arguments later. You just need to know that the main function always has this same argument.
fun main(args: Array<String>) {}
  • Notice the pair of curly braces after the arguments. Inside a function is code that accomplishes a task. These curly braces surround those lines of code.

Look at the line of code between the curly braces:

println("Happy Birthday!")

This line of code prints the Happy Birthday! text.

  • println tells the system to print a line of text.
  • Inside the parentheses you put the text to be printed.
  • Notice that the text to be printed is surrounded by quotes. This tells the system that everything inside the quotation marks should be printed exactly as given.

To actually print the text, this whole println instruction has to be inside the main function.

So, there it is. The smallest Kotlin program.

fun main(args: Array<String>) {
    println("Happy Birthday!")
}

Great job! You printed one line of text using the println() function. However, you can put as many lines of instructions inside a function as you want or need to get a task accomplished.

  1. Copy the line println("Happy Birthday!") and paste it two more times below it. Make sure your pasted lines are inside the curly braces of the main function.
  2. Change one text to be printed to someone's name, say "Jhansi".
  3. Change the other text to be printed to "You are 25!".

Your code should look like the code below.

fun main(args: Array<String>) {
    println("Happy Birthday!")
    println("Jhansi")
    println("You are 25!")
}

What would you expect this code to do when it runs?

  1. Run your program to see what it does.
  2. Go to the Console window, and you should see 3 lines printed in the console window, as shown in the screenshot below.

Nice work!

Dealing with errors

Making mistakes while programming is normal, and most tools will give you feedback to help you fix mistakes. In this step, create a mistake to see what happens.

  1. In your program, remove the quotes around the text Jhansi, so that line looks as shown below.
println(Jhansi)
  1. Run your program. You should see Jhansi printed in red, and an exclamation mark next to line 8 of the code, to show you where there is an error.

  1. Scroll down to see the console.
  2. Select the Problem view tab, if it's not selected.
  3. Look at the Problems view tab. It shows a message with the same exclamation mark icon and the word Error. What follows is a description of the error in your code.

  1. Look for numbers (8, 12). These numbers indicate the line in the code where the error occurs, line 8, and the position of the letter in that line where the error starts, which is 12.
  2. Next, you can see a message, Unresolved reference: Jhansi. This message tells you what the system thinks is the error in the code. Even if you don't know what the error message means, you may be able to figure out what's wrong. In this case, you know that the println() instruction prints text. You learned earlier that the text has to be between quotes. If the text is not quoted, that is an error.
  3. Go ahead and add the quotes back in.
  4. Run your program to make sure it works again.

Congratulations, you have run and changed your first Kotlin program!

This is the complete code of the program you worked on in this codelab.

  • https://try.kotlinlang.org/ is an interactive code editor on the web where you can practice writing Kotlin programs.
  • All Kotlin programs need to have a main() function: fun main(args: Array<String>) {}
  • Use the println() function to print a line of text.
  • Place text you want to print between double quotes. For example "Hello".
  • Repeat the println() instruction to print multiple lines of text.
  • Errors are marked red in the program. There is an error message in the Problems view tab to help you figure out where the error is and what might be causing it.

This codelab is part of the Android Basics in Kotlin course.

Do the following:

  1. Change the println() instructions to print().
  2. Run your program. What happens?

Hint: The print() instruction just prints the text without adding a line break at the end of each string.

  1. Fix the text so that each part of the message is on its own line.

Hint: Use \n inside the text to add a line break. For example, "line \n break". Adding a line break changes the output as shown below.

Hint: You can print an empty line by supplying no text: println("").

Code:

fun main(args: Array<String>) {
    println("no line break")
    println("")
    println("with line \n break")
}

Output:

Check your work:

Here is one possible solution:

fun main(args: Array<String>) {
    print("Happy Birthday!\n")
    print("Jhansi\n")
    print("You are 25!")
}