bekwam courses

Kotlin for Students #001 - First Kotlin Program

August 25, 2017

This is the first article in the Kotlin for Students series and will teach you how to run and analyze your first Kotlin program.

Usually, you'll run a Kotlin program from an application called an Integrated Development Environment or "IDE". We'll skip the software installs for now and instead work with an online resource called try.kotlinlang.org. This is a web application that lets you run Kotlin programs in your browser.

Follow this link to bring up the web application: https://try.kotlinlang.org. You should see a screen like the following image. Make sure that the "On-the-fly type checking" box is selected.

Screenshot of try.kotlinlang.org
Initial Screen from try.kotlinlang.org

To run your first Kotlin program, press the Run button in the upper-right. It's marked with a green triangle. The lower part of your screen should look like the following.

Screenshot of Lower Part of try.kotlinlang.org
Run Results Show "Hello, World!"

That's it. You ran your first Kotlin program. The program printed out the words "Hello, World!".

The Web Application

The web application at try.kotlinlang.org is divided into three sections. On the lefthand side, there is a browseable list of programs. I've labeled this the "Browser". To the right, there is a panel containing the code called the "Editor". At the bottom, there is a tabbed panel "Console". Notice that the "Console" Tab is selected. This screenshot marks the sections of the screen.

Screenshot of try.kotlinlang.org with Markings
Browser, Editor, and Console Sections

If you ever don't see your output appear in the lower section that I've labeled "Console", make sure the Console tab is selected instead of the "Problems view" or "Generated classifiers" tabs.

Analysis

One of the best ways to learn a programming language is to break down examples that you didn't write yourself. This simple program contains

  1. A comment,
  2. A main function, and
  3. A println output statement.

Comments

The text at the top of the editor beginning with "We declare..." doesn't do anything except provide a note. The way that you define a comment in Kotlin is to surround your comment with /* and */. Let's pull the comment out and verify that the program still runs the same. Highlight and delete lines 1-5 so that the top right part of the screen appears as mine does below.

Screenshot of Upper Part of try.kotlinlang.org
Same Program Minus the Comment

Re-run the program by pressing the Run button. Verify that you get the same "Hello, World!" printed at the bottom of the screen.

It's a good idea to use comments in your program to describe how something works to other team members or even to yourself. So, let's add our own comment for practice. Enter the following at the top of the editor.

/* Program run by Carl */
	

Feel free to substitute your name in the comment. Your screen should look like the following.

Screenshot of Upper Part of try.kotlinlang.org
Same Results with Custom Comment

Now, let's break the program. Try removing the */ in the comment. Notice that the color of the text changes as though the entire program were now part of the comment. Also, notice the red exclamation point circle. Hovering over that tells you that you have an enclosed comment.

Screenshot of Upper Part of try.kotlinlang.org with Red Exclamation Point
An Unclosed Comment Error

Restore the */ and make sure that you can still run your program.

Main Function

First a brief digression on functions. Even if you haven't programmed before, you should have a good idea about what a function is. Take the formula for a line from elementary school: y = mx + b. "mx + b" is a function that will return the coordinate value for y if you're given the slope (m), the x coordinate, and the y-intercept (b). You could also write this as f(m,x,b) = mx + b and say that "f is the formula for a line" and that "f takes three parameters to compute its value".

With this in mind, look at the following Kotlin code

fun main(args : Array<String>)
		

fun is a keyword in the Kotlin language indicating that the next few code elements define a function. "main" is the name of the function and "args" is a parameter for the function. Array<String> is called the type of the argument. (I'll describe what a type is in the next article. For now, just memorize that the Array<String> is a list of words.)

You should notice similarities between the line formula "f(m,x,b)" and the Kotlin function fun main(args : Array<String>). Kotlin adds the keyword "fun" which isn't needed in the mathematics example. "f" is the function name for the line formula; "main" is the function name in the Kotlin program. "m,x,b" are three parameters for the line formula; "args" is the single parameter for the Kotlin main function. Kotlin specifies a type "Array<String>" for the parameter "args"; the line formula assumes three numbers.

Running a Main

The main function has a special status in Kotlin. When you press the Run button, you're telling Kotlin to run the program in the editor. Kotlin needs to know where the program begins. That's the purpose of the main function. When asked to run a program, Kotlin will look for a main function and start running the sequence of statements in the function. There can be one and only one main function per program.

Any main function must contain the following four items

  1. The keyword 'fun' which indicates that you are defining a function,
  2. The reserved word 'main' which indicates a main function,
  3. A parameter "args" of type Array<String>, and
  4. A body containing a sequence of statements surrounded by { and }.

Items 1, 2, and 3 make up the function definition and were described in the previous sections by comparing and contrasting with the line formula. Item 4 -- the body -- is the sequence of statements that do the work of the function. These statements can be computations or commands. The body is surrounded by curly braces {} and each statement ends with a return character also called a "newline".

The body of this main function contains a single statement "println" described below.

Println

println is a function provided by Kotlin to write output to the Console. At the bottom of the try.kotlinlang.org screen, notice that the tab "Console" is selected. "println" stands for "Print Line" and in addition to printing the characters "Hello, world!", it prints a return character.

Let's add a second println() function call. Copy the println("Hello, world!") line and modify the characters in the second call to be "Goodbye, world!". Your screen should look like the following.

Screenshot of Editor Showing Code
println() Duplicated with Second Message

Press the Run button. You should see the following at the bottom of the screen.

Screenshot of Console Showing Results
Two println() Messages

println(), like main(), is a function. println() is different in that you did not provide a definition for it. println() is available to you because Kotlin ships a Standard Library of functions. This web page provided by JetBrains describes println(). Don't worry about the multiple listings of println(); we'll discuss those when we get to types. The specific call we made is "inline fun println(message : CharArray)".

Screenshot of Kotlin Docs Webpage
Section of println() in the Kotlin Docs

Analyzing the println() from the Kotlin Docs definition, there is a new keyword "inline" that appears in front of the familiar keyword "fun". Don't worry about inline for now. That's a performance optimization used in advanced function-writing cases. Just note that the "fun" keyword is there. The name of the function is "println". The println function takes a single argument "message". There is a type associated with "message" called "CharArray".

"message" is a sequence of characters such as "Hello, world!" or "Goodbye, world!".

There are many other functions available off-the-shelf with Kotlin. You can also look for open source and commercial projects for even more functions. You'll create many yourself following these articles.

Wrap Up

This article showed you the online resource try.kotlinlang.org which let you run Kotlin programs without having to install any special software. We ran a program provided by the web site that printed "Hello, World!" to the console. We modified the program to print out a different message and we also edited the comment appearing at the top of the screen.

Go Further

You've learned how to modify the arguments to the println() function. Copy the line again and put a new message in between the double quotes. While you're at it, tweak your comment.

Break something. From a working program, delete the last curly brace }. Do you see an error displayed almost immediately? Restore the curly brace so that the errors clear up and Run the program to double-check that it's still working. Delete the closing parenthesis ) in one of the println calls. Do you see an error? Try to run the program. Restore the ) and make sure the program is still working.

Finally, delete one of the double-quotes " from one of the println() calls. Verify that you get an error immediately and restore the ".


Headshot of Carl Walker

By Carl Walker

President and Principal Consultant of Bekwam, Inc