Linux Format

Kotlin primer..........................

Mihalis Tsoukalos shows you how to start using Kotlin by explaining basic concepts so you can get stuck in with this interestin­g language…

-

Mihalis Tsoukalos shows you how to start using Kotlin by explaining basic concepts, so you can get stuck in coding command line tools with what he calls an “interestin­g” language…

This is an introducto­ry tutorial to the Kotlin programmin­g language. After reading this article you’ll be able to install Kotlin, and know how to execute Kotlin code and understand the structure of Kotlin programs.

However, because this is the first tutorial in the Kotlin series, it won’t go into too much depth. Forthcomin­g tutorials will explore many important Kotlin topics including Kotlin data types as well as object-oriented programmin­g, systems programmin­g and web developmen­t, so make sure that you understand the concepts presented in this month’s tutorial. The best way to take advantage of this advice revealed here is to try to develop your own Kotlin programs using the presented code as a point of reference. After all, you can only learn programmin­g by writing code!

The Android connection

The big news is that Kotlin can be officially used for developing Android applicatio­ns, which automatica­lly makes Kotlin a major player in the programmin­g languages area. What’s important to understand is that Kotlin uses the Java Virtual Machine (JVM), which means that Java is still there for you and that your existing Java knowledge is still valid, even if that happens behind the scenes! Additional­ly, Kotlin makes use of the standard Java libraries.

If you like Java, you’ll most likely enjoy developing software in Kotlin, which is much easier to learn. However, if you’re not a big fun of Java, you might still like Kotlin, so give it a try – you won’t regret it! First of all, Kotlin code is clean and simple, which means that it’s also easy to read, in fact much easier to read than Java code. Additional­ly, Kotlin is a safe programmin­g language that can save you from null pointer exceptions. It also offers many advanced features including Static typing, Extensions, Lambdas and Delegated properties. Finally, Kotlin requires less coding compared to Java.

Figure 1 ( above) shows the initial screen of the official Kotlin site, which can be found at https://kotlinlang.org.

Installing Kotlin

Strictly speaking, Kotlin is a statically typed programmin­g language for the Java Virtual Machine. However, none of its characteri­stics will make sense unless you install it on your Linux machine. The installati­on process on an Ubuntu Linux machine includes the following steps: $ wget -O sdk.install.sh “https://get.sdkman.io” $ vi sdk.install.sh $ bash sdk.install.sh

The second step is optional and you’ll most likely not need to make any changes to sdk.install.sh so don’t worry about it – you can just look at its contents. The third step is where the actual installati­on of Kotlin starts taking place.

After performing the third step, you’re advised to execute the next command, which is for setting up the Kotlin environmen­t for the current user:

$ source “/home/mtsouk/.sdkman/bin/sdkman-init.sh” So far you’ve just installed the sdk tool that will help you install Kotlin proper: $ sdk install kotlin

Because Kotlin needs a Java installati­on, you might need to execute sudo apt-get install openjdk-8-jre-headless on your Ubuntu machine. After that, you’ll be ready to start writing Kotlin programs. But first, you can find the version of Kotlin you’re using by executing the next command: $ kotlinc -version info: kotlinc-jvm 1.1.3-2 (JRE 1.8.0_131-8u131-b112ubuntu­1.16.04.2-b11)

As you can see, the Java version you’re using is also mentioned in the previous output because Kotlin is based on Java. This also means that you might see some Java error messages while writing software in Kotlin.

Now that you’ve Kotlin successful­ly installed, it’s time to start looking at some Kotlin code!

Hello Kotlin!

This section will gently present you some Kotlin code and the various methods of executing it – the HelloWorld program will be used as an example. The Kotlin version of the Hello World program is as follows: package hw fun main(args: Array<String>) { println("Hello World!") }

Kotlin code is usually included in packages because packages enable us to split Kotlin code into separate namespaces – in this case the name of the package is hw and contains a simple function called main() , which is where the execution of an autonomous Kotlin program begins. Although using packages is a good practice, you’re not obliged to get involved with them.

As you can also see, semicolons are optional in Kotlin, which is also true for most modern programmin­g languages. Additional­ly, you can see that you can print output on the screen using the println() function. There’s also the print() function that does the same job as println() without automatica­lly inserting a new line character at the end of its output. Finally, by looking at the way the main() function is defined you can tell that function’s definition­s in Kotlin start with the fun keyword.

Please note that the same program can be written using objects and classes, which will be presented and explained in a forthcomin­g tutorial.

If you save the previous code in a file named hw.kt, then you can compile it into a JAR file as follows: $ kotlinc hw.kt -include-runtime -d hw.jar $ file hw.jar hw.jar: Java archive data (JAR) $ ls -l hw.jar -rw-rw-r-- 1 mtsouk mtsouk 865307 Jul 31 11:00 hw.jar

The -include-runtime command line option instructs the compiler to create an autonomous and runnable JAR file by telling the compiler to include the Kotlin runtime into the generated file. This is the main reason why the hw.jar file is so big. The -d flag that’s also used enables you to specify the name of the JAR file which is going to be generated.

When the previous command is executed successful­ly, it generates no output on your screen. After that, you can execute hw.jar using Java in order to see the desired output: $ java -jar hw.jar Hello World! Because Kotlin supports scripts, you can also make Hello World program a Kotlin script, named hw.kts: println("Hello, world!")

So, when you’re creating a Kotlin script, there’s no need to have a main() function. Next, you can execute hw.kts as follows: $ kotlinc -script hw.kts Hello, world! The only difference here is initiated by the -script option.

So far, you’ve learnt how to execute Kotlin code in two different ways. Next, you’ll learn is that Kotlin offers an interactiv­e shell that you can enter if you execute kotlinc-jvm.

Figure 2 ( ontheprevi­ouspage) shows an interactio­n with the Kotlin interactiv­e shell. The interactiv­e shell, which is also called REPL, is the perfect place to try new things, make mistakes and learn – so don’t hesitate to use it.

Variabilit­y

As you might expect, Kotlin enables you to define new variables, change the value of old ones as well as combine existing variables to create new ones.

First of all you should be aware that Kotlin supports two kinds of variables: mutable and immutable. Mutable variables are declared using the var keyword and immutable variables are defined using the val keyword. An immutable variable must be initialise­d when they’re created, because their value can’t change afterwards.

The following interactio­n will take place in the REPL: >>> var str1 = “This is ">>> var str2 = “a String!” >>> val s1s2 = str1 + str2 >>> println(s1s2) This is a String!

The aforementi­oned code defines three string variables named str1, str2 and s1s2 and demonstrat­es that you can link strings together using the + operator.

Figure 3 ( below) displays further examples of variable definition­s that sit inside the Kotlin REPL. As you can see, if you attempt to change the value of an immutable variable, you’ll receive an error message, which is the case with the s2 variable.

Need input!

Being able to obtain user input is very important; so we’re going to show a way of getting informatio­n from users in Kotlin. The name of the program will be userInput.kt – its most important code is the implementa­tion of the main() function: fun main(args: Array<String>) { println("Enter Two numbers:") var (a,b) = readLine()!!.split(’ ‘) println("Min of $a and $b is: ${findMin(a.toInt(), b. toInt())}") }

Here you can see a technique for reading two values from the user that will be saved in the a and b variables, using a single Kotlin statement.

If you execute userInput you’ll have the next type of interactio­n with it: $ kotlinc userInput.kt -include-runtime -d userInput.jar $ java -jar userInput.jar Enter Two numbers: 12 Min of 1 and 2 is: 1

The Kotlin code of the entire userInput.kt program can be seen in Figure 4 ( above). If you look carefully enough at this screenshot, you’ll understand that Kotlin supports two kinds of comments: line and block. Line comments begin with // whereas block comments begin with /* and end with */ .

There are alternativ­e ways to obtain data from the user – the method discussed here is handy when you want to read just two values from the user.

Taking arguments

Let’s take a small Kotlin program that finds the sum of its command line arguments, provided that they have valid numeric values. As you show in hw.kt and userInput.kt, the main() function takes one argument named args that’s an array of string variables. These are the command line arguments of your program and are automatica­lly assigned by the compiler, which is also the case in the majority of programmin­g languages.

The name of the next program is args.kt and contains the following sample of Kotlin code: fun main(args: Array<String>) { if (args.size == 0) { println("Please give me at least one argument!") return } println("1st argument: ${args[0]}!") for (k in args)

println("$k") }

The first thing this program does is make sure that it’s given at least one command line argument. Failing to test this might make your program crash.

You can also see here how you can access array elements in Kotlin: the first element of the args array can be accessed as args[0] , the second as args[1] , and so on.

However, args.kt reveals an additional method of accessing the command line arguments of your program – the second technique uses a for loop and won’t crash if there aren’t enough command line arguments. Neverthele­ss, if you want to process a particular command line argument, it makes more sense to access it directly.

Compiling and executing args.kt will create the following kind of output: $ kotlinc args.kt -include-runtime -d args.jar $ java -jar args.jar Please give me at least one argument! $ java -jar args.jar 1 2 1st argument: 1! 1 2

It’s now time to see the Kotlin code of the program that finds the sum of its command line arguments – this is presented in Figure 5 ( aboveright). If you understand the code of args.kt, then you’ll have no problem grasping the ideas behind the code of sumArgs.kt.

Please note that the toInt() function converts a string that represents an integer to an actual integer value – in this case toInt() is used to convert the command line arguments of

sumArgs.kt to their integer values. Although Kotlin has exception handling capabiliti­es that are similar to Java, the relevant code was omitted here for reasons of simplicity and code clarity.

Compiling and executing sumArgs.kt will generate the following type of output: $ kotlinc sumArgs.kt -include-runtime -d sumArgs.jar $ java -jar sumArgs.jar 1 2 3 4 5 Sum: 15

Functions in

In this section you’re going to learn some basic things about Kotlin functions. The function that’s going to be implemente­d here will calculate natural numbers that belong to the wellknown Fibonacci sequence. The name of the Kotlin program will be fibo.kt and the implementa­tion of the fibo() function is the following: fun fibo(n: Int): Unit {

var f1 = 0 var f2 = 1 for (i in 1..n) { print("$f1 -- “) val newTerm = f1 + f2 f1 = f2 f2 = newTerm }

}

As you already know, function definition­s in Kotlin begin with the keyword ‘fun’. Additional­ly, the type of the return value of a Kotlin function is defined using a colon after the function. If a function has nothing to return, then you can put Unit as its return type. However, you’re also free to omit the return type for such functions – that’s why the main() function presented in hw.kt has no return type. Therefore, the next two function declaratio­ns are completely equivalent: fun fibo(n: Int): Unit fun fibo(n: Int) If you compile and execute fibo.kt you’ll produce the following kind of output: $ kotlinc fibo.kt -include-runtime -d fibo.jar $ java -jar fibo.jar 10 Fibonacci Sequence: 0 --1 -- 1 -- 2 -- 3 -- 5 -- 8 -- 13 -- 21 -- 34 --

Kotlin functions can carry out many more things than the ones presented here – wait until the Kotlin tutorial of the next LinuxForma­t issue to learn more!

Sooner rather than later, you’ll have to try Kotlin, you’ll start developing systems software and new Android applicatio­ns and maybe start rewriting old ones in Kotlin so why not start learning Kotlin today? And if you run into the odd difficulty, don’t worry. LinuxForma­t is here to help! LXF

 ??  ?? Figure 3 uses the Kotlin REPL to illustrate Kotlin mutable and immutable variables as well as Kotlin arrays.
Figure 3 uses the Kotlin REPL to illustrate Kotlin mutable and immutable variables as well as Kotlin arrays.
 ??  ?? Figure 4 displays the Kotlin code of userInput.kt, which is a program that reads two integers and calculates the smaller integer of the two.
Figure 4 displays the Kotlin code of userInput.kt, which is a program that reads two integers and calculates the smaller integer of the two.
 ??  ?? Figure 2 shows a small interactio­n with the Kotlin REPL, which is an interactiv­e Kotlin shell where you can try things without fear of breaking anything!
Figure 2 shows a small interactio­n with the Kotlin REPL, which is an interactiv­e Kotlin shell where you can try things without fear of breaking anything!
 ??  ??
 ??  ?? Figure 1 shows the initial screen of the official Kotlin web site, which you should regularly visit to get informatio­n on the latest updates about the programmin­g language.
Figure 1 shows the initial screen of the official Kotlin web site, which you should regularly visit to get informatio­n on the latest updates about the programmin­g language.
 ??  ?? Mihalis Tsoukalos is a UNIX administra­tor, a programmer, a DBA and a mathematic­ian who enjoys writing articles and learning new things in life.
Mihalis Tsoukalos is a UNIX administra­tor, a programmer, a DBA and a mathematic­ian who enjoys writing articles and learning new things in life.
 ??  ?? Figure 5 demonstrat­es the Kotlin code of sumArgs.kt, which is a program that finds the sum of its integer command line arguments.
Figure 5 demonstrat­es the Kotlin code of sumArgs.kt, which is a program that finds the sum of its integer command line arguments.

Newspapers in English

Newspapers from Australia