paint-brush
How to Write Your First Program in Kotlin?by@oleksii_f
7,413 reads
7,413 reads

How to Write Your First Program in Kotlin?

by Oleksii FedorovFebruary 25th, 2018
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

I’ve heard you want to learn to program.

Company Mentioned

Mention Thumbnail
featured image - How to Write Your First Program in Kotlin?
Oleksii Fedorov HackerNoon profile picture

I’ve heard you want to learn to program.

Most likely you are looking into Kotlin because you wanted to create an Android application. Or, perhaps, you are trying to get your hand at the back-end web development.

Whichever the case, Kotlin is a pretty good language to start.

You’ve been already looking for a good tutorial, but one way or another, they all require previous Java knowledge.

Isn’t that unfortunate?

From a perspective of a beginner — definitely is!

Well then, you’ll find that this multi-part tutorial is just what you need, as it doesn’t assume any previous programming experience.

This tutorial is not going to go into the Android world, or web development world, for that matter, but it is going to give you a firm foundation to start your programming journey.

“Your programming journey” (source: pexels)

But before you begin:

What do I need to have installed on my computer?

  • Terminal application.
  • Simple text editor with Kotlin syntax highlighting support (for example: Atom + kotlin package works well).

PS: if you need help installing a Kotlin package in Atom, here is the tutorial for that on Atom’s official manual.

PPS: why not use IntelliJ IDEA, or some other IDE?

As much as I love IntelliJ, I understand that it could be quite confusing for a beginner developer.

Also, that would not allow you to learn the program development cycle (edit, compile, run) because IDE will do everything for you.

If you are already a seasoned programmer, and you don’t need such details, and you just want to learn some Kotlin, use any editor or IDE that you like. Keep in mind, though: this tutorial is going to use kotlinc compiler.

And in one of my advanced tutorials we are using IDE to its fullest.

  • JDK (for your platform: Mac OS X, Linux, Windows) is required to run programs compiled by Kotlin compiler.

  • Kotlin compiler [kotlinc](https://kotlinlang.org/docs/tutorials/command-line.html). Once installed correctly you should be able to run command kotlinc -version in the terminal application:

    $ kotlinc -versioninfo: kotlinc-jvm 1.2.21 (JRE 1.8.0_152-b16)

The version may vary, as authors of the language (JetBrains) update the language quite often.

But You Said I Don’t Need Java…

As you were going through the process of installation of the JDK, you probably wondered, why you are installing some Java stuff.

And I just told you that this guide wouldn’t require knowledge of Java, didn’t I?

So, here is the thing.

While Kotlin is an independent language of its own, it does rely on Java’s standard library and development kit.

You don’t have to give it enough thought right now. All it will do for you in your first applications is help the Kotlin to build and run your applications. When pertinent, we are going to address the issue.

That out of the picture (for now), we should dive into creating your first program in Kotlin right away!

Hello World — Boring… Boring?

I know it’s boring, and you, perhaps, already have seen it a few times, but in this article, we are not just going to create and run your “Hello World” program, but we’ll:

  • Understand the program’s code and all parts that it consists of.
  • Explore what happens when you build and run your application.

Additionally, you are going to learn what kind of errors can happen in programming, and as part of the exercises:

  • You are going to print something more interesting on the screen.
  • You are going to break the program in various ways so that you can experience all the mentioned kinds of errors of the development cycle.

Speaking of which…

Development Cycle in Kotlin

In Kotlin we break the process of programming in a few steps:

  1. Write the program by typing it in your text editor and save it to the file ProgramName.kt.
  2. Compile it by typing kotlinc ProgramName.kt -include-runtime -d ProgramName.jar in the terminal application. We’ll talk about parts of this command in a bit.
  3. Run the compiled program by typing java -jar ProgramName.jar in the terminal application.

In the first step, you are going to create a human-readable representation of the program using Kotlin programming language.

The second step translates the human-readable program into a language that is suitable for machine execution. -d ProgramName.jar option specifies in which file the result will be written. And -include-runtime tells Kotlin compiler to include its standard library. Without that option, you are going to see a runtime error on the next step.

The third step runs the program.

Let’s see how that all will look like for the “Hello World” program:

Creating Your First Program in Kotlin

Writing a Kotlin program.

A program is a sequence of characters (such as letters, numbers, spaces and special signs). It is just like a sentence, paragraph or a poem.

To write a program, you need to type these characters using your text editor and save it into the file called HelloWorld.kt:

Compiling a Kotlin program

A Kotlin compiler (kotlinc) is an application that translates programs you write in Kotlin language to a language more suitable for execution on the computer.

It takes a regular text file with extension .kt (that contains your program) as an input and creates a file with .jar extension (the version suitable for execution on the computer).

To compile your Kotlin program HelloWorld.kt type the following text in your terminal:

kotlinc HelloWorld.kt -include-runtime -d HelloWorld.jar

If you typed the program correctly, you should see no errors. If you made a typo somewhere you’d see error output similar to that:

HelloWorld.kt:1:14: error: expecting comma or ')'fun main(args Array<String>) {             ^HelloWorld.kt:1:15: error: parameter name expectedfun main(args Array<String>) {              ^HelloWorld.kt:1:10: error: a type annotation is required on a value parameterfun main(args Array<String>) {         ^

This output indicates that there was a compile error. If you get something like that, make sure you typed the HelloWorld.kt program correctly. Check character by character if you must.

When your program compiles successfully — you should see no output. Usually, any output from Kotlin compiler indicates an error of sort or a warning.

Running a Kotlin program

When you have a compiled program, you can run it. When the computer runs your application, it follows the instructions you provided precisely.

This fact is the most significant part of programming — you can make your computer do what you want precisely.

To run your HelloWorld.jar program, type the following command in the terminal:

java -jar HelloWorld.jar

If everything is correct, you’ll see the expected output in the terminal:

Hello World

Understanding the program

println() line is the most important one in the file HelloWorld.kt. That line is the one doing the printing of the “Hello World” text in the terminal. We are going to tackle other parts of the program, such as fun, args, Array<String>, later when we are going to write more complex applications.

println() function is printing the provided text on the standard output. Standard output usually is the same as the output in the terminal, but not always. Sometimes, standard output can be redirected somewhere else, for example into the file.

The text "Hello World" is a string literal. String literal is a literal that represents a fixed value of the text (String type) in the source code of your program. We are going to get back to types and literals later.

Creating your program

For now, all of your programs will be simple and just like HelloWorld.kt. The only difference will be the sequence of statements that you are going to put inside of the main() function. The simplest way to create your program is to:

  • Copy contents of HelloWorld.kt into MyProgram.kt (where “MyProgram” is the name of your new program)
  • Replace println() statement with your sequence of statments:

Errors

Whatever you do, there will be errors when programming. They can be fixed by carefully examining the program (like you do when fixing grammar and spelling mistakes in a message to your friend). There are few kinds of errors that you are going to encounter:

Compile-time errors

The Kotlin compiler catches these errors. Such errors happen because the source code is not structured quite right, and the Kotlin compiler can’t understand what you’re trying to tell it.

Kotlin compiler will tell you where in the source code there is an error, and what was the compiler expecting instead. Kotlin compiler will try to explain why it is unable to translate the code to the machine-executable language.

Run-time errors

These errors are caught by the execution system when you are running the program (when you are running java -jar HelloWorld.jar, for example). Such errors happen because the program is trying to perform an invalid operation, for example:

  • division by zero,
  • trying to access the data that doesn’t exist,
  • trying to read a file that you don’t have permission to read,
  • trying to access the resource on the internet that is not available,
  • and so on.

Logical errors

These errors are, also, called bugs. These errors usually mean that the program produces the wrong answer or incorrect result at run-time.

For example, if you had a program, that asks the user for two numbers and prints out the sum of these two numbers. And when the user has entered 7 and 5, the program has printed 13 instead of 12. That is a wrong answer, and therefore the program has a logical error (a bug).

It is entirely up to the programmer to inspect the wrong result and the source code of the program to find out why it behaves incorrectly. When you, as a programmer, have found out that “why” you should be able to fix the bug.

Logical errors are the hardest ones. They can be subtle, non-reproducible, and hard to find.

As a programmer, it is essential to be able to identify with what kind of error you are dealing with, and carefully examine your source code to find the reason of the failure, and fix it. That is one of the first skills that you should learn via exercises and practice.

Given enough practice, you should become better and better at avoiding these kinds of errors. Writing programs is an activity that requires constant carefulness and diligence.

Input And Output

Wouldn’t it be wonderful to write a program, that not only outputs text on the screen but also interacts with the user?

That is a typical use case for any program. Very few applications don’t require any user input, so you’ll have to learn how to do that.

There are two simple ways to do that in the world of command-line applications.

(and you don’t want to jump straight into the world of graphical or mobile applications, as complexity there is very high — foundations first)

Command-line Arguments

The first way is to read user input from the command-line arguments. For example, to access the first command-line argument you would use args[0]. For second—args[1]. For third—args[2]. And so on.

Here is the example program that reads the first argument: ReadFirstArgument.kt:

Now try to compile:

kotlinc ReadFirstArgument.kt -include-runtime -d ReadFirstArgument.jar

And run it:

java -jar ReadFirstArgument.jar Peter

You should see the expected output:

Hello, Peter! How are things going?

Try to replace “Peter” argument with your first name. It should greet you and ask how are your things going!

Reading From Standard Input

Now, this method is a bit more interactive, but, also, more complicated. It is going to involve some concepts that we’ll go through a bit later.

First, we are going to ask the user to enter their name, and we are going to read the user input into a local variable name (about local variables—later):

Most important part here is readLine(). It is reading the user input until the end of the line (when the user presses “Enter”).

Then we are going to use the local variable name just as we used args[0] in the previous program:

To write such program, create the file ReadFromInput.kt and type the following in your text editor:

Then you compile that program using kotlinc … command and run it using java -jar … command. When you’ve done that right, you should see the following when you run the program:

What is your name? > Mary

Hello, Mary! How are things going?

(emphasis is on what user has typed)

Try to use some other name — it should work just as you expect.

Exercises


  • Write a program HelloWorldMultipleTimes.kt that will output “Hello World” fifteen times.If you are stuck or want to check the answer find solution here.


  • Write a program ReadTwoArguments.kt that will read first and second command-line argument, and output them as the first name and second name of the user.If you are stuck or want to check the answer find solution here.


  • Write a program ReadMutlipleInputs.kt that will ask the user for their first name, and then ask them for their second name. Finally, the program should greet the user by the combination of their first and last names.If you are stuck or want to check the answer find solution here.











  • In HelloWorld.kt, what happens if you remove:* main,* fun,* println,* "Hello World",* {,* },* first ",* second "?What kind of error is that (for each option above)?If you are stuck or want to check the answer find solution here.



  • When compiling HelloWorld.kt, what happens if you don’t specify: -include-runtime?If you are stuck or want to check the answer find solution here.

  • Write a program AsciiArtHello.kt that will output the following in the terminal:

    ## ######### ## ## ########### ## ## ## ## ## #### ## ## ## ## ## ########### ######### ## ## ## ########### ######### ## ## ## #### ## ## ## ## ## #### ## ## ## ## ## #### ## ######### ######### #########

If you are stuck or want to check the answer find solution here.

  • When running program ReadFirstArgument, if you don’t provide the first argument like so:

    java -jar ReadFirstArgument.jar

What kind of error will happen?

If you are stuck or want to check the answer find solution here.

  • I have written the following program HelloWeird.kt:

What is wrong with this program? What happens if you compile and run it? How to fix this program?

If you are stuck or want to check the answer find solution here.

My related articles


Why Should I Learn Android?_You have firmly decided that you want to learn to create applications for Android using Kotlin. You are super motivated…_hackernoon.com


How to Find The Time to Learn a New Skill When You Are Working Full-Time?_Let me guess…_hackernoon.com


How Kotlin Calamity Devours Your Java Apps Like Lightning?_I hear what you are saying. There is that buzz around Android actively adopting Kotlin as a primary programming…_hackernoon.com