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

Mi­halis Tsouka­los shows you how to start us­ing Kotlin by ex­plain­ing ba­sic con­cepts so you can get stuck in with this in­ter­est­ing lan­guage…

Linux Format - - CONTENTS -

Mi­halis Tsouka­los shows you how to start us­ing Kotlin by ex­plain­ing ba­sic con­cepts, so you can get stuck in cod­ing com­mand line tools with what he calls an “in­ter­est­ing” lan­guage…

This is an in­tro­duc­tory tu­to­rial to the Kotlin pro­gram­ming lan­guage. Af­ter read­ing this ar­ti­cle you’ll be able to install Kotlin, and know how to ex­e­cute Kotlin code and un­der­stand the struc­ture of Kotlin pro­grams.

How­ever, be­cause this is the first tu­to­rial in the Kotlin series, it won’t go into too much depth. Forth­com­ing tu­to­ri­als will ex­plore many im­por­tant Kotlin top­ics in­clud­ing Kotlin data types as well as ob­ject-ori­ented pro­gram­ming, sys­tems pro­gram­ming and web de­vel­op­ment, so make sure that you un­der­stand the con­cepts pre­sented in this month’s tu­to­rial. The best way to take ad­van­tage of this ad­vice re­vealed here is to try to de­velop your own Kotlin pro­grams us­ing the pre­sented code as a point of ref­er­ence. Af­ter all, you can only learn pro­gram­ming by writ­ing code!

The An­droid con­nec­tion

The big news is that Kotlin can be of­fi­cially used for de­vel­op­ing An­droid ap­pli­ca­tions, which au­to­mat­i­cally makes Kotlin a ma­jor player in the pro­gram­ming lan­guages area. What’s im­por­tant to un­der­stand is that Kotlin uses the Java Vir­tual Ma­chine (JVM), which means that Java is still there for you and that your ex­ist­ing Java knowl­edge is still valid, even if that hap­pens be­hind the scenes! Ad­di­tion­ally, Kotlin makes use of the stan­dard Java li­braries.

If you like Java, you’ll most likely en­joy de­vel­op­ing soft­ware in Kotlin, which is much eas­ier to learn. How­ever, if you’re not a big fun of Java, you might still like Kotlin, so give it a try – you won’t re­gret it! First of all, Kotlin code is clean and sim­ple, which means that it’s also easy to read, in fact much eas­ier to read than Java code. Ad­di­tion­ally, Kotlin is a safe pro­gram­ming lan­guage that can save you from null pointer ex­cep­tions. It also of­fers many ad­vanced fea­tures in­clud­ing Static typ­ing, Ex­ten­sions, Lamb­das and Del­e­gated prop­er­ties. Fi­nally, Kotlin re­quires less cod­ing com­pared to Java.

Fig­ure 1 ( above) shows the ini­tial screen of the of­fi­cial Kotlin site, which can be found at https://kotlin­lang.org.

In­stalling Kotlin

Strictly speak­ing, Kotlin is a stat­i­cally typed pro­gram­ming lan­guage for the Java Vir­tual Ma­chine. How­ever, none of its char­ac­ter­is­tics will make sense un­less you install it on your Linux ma­chine. The in­stal­la­tion process on an Ubuntu Linux ma­chine in­cludes the fol­low­ing steps: $ wget -O sdk.install.sh “https://get.sd­kman.io” $ vi sdk.install.sh $ bash sdk.install.sh

The sec­ond step is op­tional 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 con­tents. The third step is where the ac­tual in­stal­la­tion of Kotlin starts tak­ing place.

Af­ter per­form­ing the third step, you’re ad­vised to ex­e­cute the next com­mand, which is for set­ting up the Kotlin en­vi­ron­ment for the cur­rent user:

$ source “/home/mt­souk/.sd­kman/bin/sd­kman-init.sh” So far you’ve just in­stalled the sdk tool that will help you install Kotlin proper: $ sdk install kotlin

Be­cause Kotlin needs a Java in­stal­la­tion, you might need to ex­e­cute sudo apt-get install open­jdk-8-jre-head­less on your Ubuntu ma­chine. Af­ter that, you’ll be ready to start writ­ing Kotlin pro­grams. But first, you can find the ver­sion of Kotlin you’re us­ing by ex­e­cut­ing the next com­mand: $ kotlinc -ver­sion info: kotlinc-jvm 1.1.3-2 (JRE 1.8.0_131-8u131-b112ubuntu1.16.04.2-b11)

As you can see, the Java ver­sion you’re us­ing is also men­tioned in the pre­vi­ous out­put be­cause Kotlin is based on Java. This also means that you might see some Java er­ror mes­sages while writ­ing soft­ware in Kotlin.

Now that you’ve Kotlin suc­cess­fully in­stalled, it’s time to start look­ing at some Kotlin code!

Hello Kotlin!

This sec­tion will gen­tly present you some Kotlin code and the var­i­ous meth­ods of ex­e­cut­ing it – the Hel­loWorld pro­gram will be used as an ex­am­ple. The Kotlin ver­sion of the Hello World pro­gram is as fol­lows: pack­age hw fun main(args: Ar­ray<String>) { println("Hello World!") }

Kotlin code is usu­ally in­cluded in pack­ages be­cause pack­ages en­able us to split Kotlin code into sep­a­rate names­paces – in this case the name of the pack­age is hw and con­tains a sim­ple func­tion called main() , which is where the ex­e­cu­tion of an au­ton­o­mous Kotlin pro­gram be­gins. Al­though us­ing pack­ages is a good prac­tice, you’re not obliged to get in­volved with them.

As you can also see, semi­colons are op­tional in Kotlin, which is also true for most mod­ern pro­gram­ming lan­guages. Ad­di­tion­ally, you can see that you can print out­put on the screen us­ing the println() func­tion. There’s also the print() func­tion that does the same job as println() with­out au­to­mat­i­cally in­sert­ing a new line char­ac­ter at the end of its out­put. Fi­nally, by look­ing at the way the main() func­tion is de­fined you can tell that func­tion’s def­i­ni­tions in Kotlin start with the fun key­word.

Please note that the same pro­gram can be writ­ten us­ing ob­jects and classes, which will be pre­sented and ex­plained in a forth­com­ing tu­to­rial.

If you save the pre­vi­ous code in a file named hw.kt, then you can com­pile it into a JAR file as fol­lows: $ kotlinc hw.kt -in­clude-run­time -d hw.jar $ file hw.jar hw.jar: Java ar­chive data (JAR) $ ls -l hw.jar -rw-rw-r-- 1 mt­souk mt­souk 865307 Jul 31 11:00 hw.jar

The -in­clude-run­time com­mand line op­tion in­structs the com­piler to cre­ate an au­ton­o­mous and runnable JAR file by telling the com­piler to in­clude the Kotlin run­time into the gen­er­ated file. This is the main rea­son why the hw.jar file is so big. The -d flag that’s also used en­ables you to spec­ify the name of the JAR file which is go­ing to be gen­er­ated.

When the pre­vi­ous com­mand is ex­e­cuted suc­cess­fully, it gen­er­ates no out­put on your screen. Af­ter that, you can ex­e­cute hw.jar us­ing Java in or­der to see the de­sired out­put: $ java -jar hw.jar Hello World! Be­cause Kotlin sup­ports scripts, you can also make Hello World pro­gram a Kotlin script, named hw.kts: println("Hello, world!")

So, when you’re cre­at­ing a Kotlin script, there’s no need to have a main() func­tion. Next, you can ex­e­cute hw.kts as fol­lows: $ kotlinc -script hw.kts Hello, world! The only dif­fer­ence here is ini­ti­ated by the -script op­tion.

So far, you’ve learnt how to ex­e­cute Kotlin code in two dif­fer­ent ways. Next, you’ll learn is that Kotlin of­fers an in­ter­ac­tive shell that you can en­ter if you ex­e­cute kotlinc-jvm.

Fig­ure 2 ( on­thep­re­vi­ous­page) shows an in­ter­ac­tion with the Kotlin in­ter­ac­tive shell. The in­ter­ac­tive shell, which is also called REPL, is the per­fect place to try new things, make mis­takes and learn – so don’t hes­i­tate to use it.

Vari­abil­ity

As you might ex­pect, Kotlin en­ables you to de­fine new vari­ables, change the value of old ones as well as com­bine ex­ist­ing vari­ables to cre­ate new ones.

First of all you should be aware that Kotlin sup­ports two kinds of vari­ables: mu­ta­ble and im­mutable. Mu­ta­ble vari­ables are de­clared us­ing the var key­word and im­mutable vari­ables are de­fined us­ing the val key­word. An im­mutable vari­able must be ini­tialised when they’re cre­ated, be­cause their value can’t change af­ter­wards.

The fol­low­ing in­ter­ac­tion 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 afore­men­tioned code de­fines three string vari­ables named str1, str2 and s1s2 and demon­strates that you can link strings to­gether us­ing the + op­er­a­tor.

Fig­ure 3 ( be­low) dis­plays fur­ther ex­am­ples of vari­able def­i­ni­tions that sit in­side the Kotlin REPL. As you can see, if you at­tempt to change the value of an im­mutable vari­able, you’ll re­ceive an er­ror mes­sage, which is the case with the s2 vari­able.

Need in­put!

Be­ing able to ob­tain user in­put is very im­por­tant; so we’re go­ing to show a way of get­ting in­for­ma­tion from users in Kotlin. The name of the pro­gram will be userIn­put.kt – its most im­por­tant code is the im­ple­men­ta­tion of the main() func­tion: fun main(args: Ar­ray<String>) { println("En­ter Two num­bers:") var (a,b) = read­Line()!!.split(’ ‘) println("Min of $a and $b is: ${find­Min(a.toInt(), b. toInt())}") }

Here you can see a tech­nique for read­ing two val­ues from the user that will be saved in the a and b vari­ables, us­ing a sin­gle Kotlin state­ment.

If you ex­e­cute userIn­put you’ll have the next type of in­ter­ac­tion with it: $ kotlinc userIn­put.kt -in­clude-run­time -d userIn­put.jar $ java -jar userIn­put.jar En­ter Two num­bers: 12 Min of 1 and 2 is: 1

The Kotlin code of the en­tire userIn­put.kt pro­gram can be seen in Fig­ure 4 ( above). If you look care­fully enough at this screen­shot, you’ll un­der­stand that Kotlin sup­ports two kinds of com­ments: line and block. Line com­ments be­gin with // whereas block com­ments be­gin with /* and end with */ .

There are al­ter­na­tive ways to ob­tain data from the user – the method dis­cussed here is handy when you want to read just two val­ues from the user.

Tak­ing ar­gu­ments

Let’s take a small Kotlin pro­gram that finds the sum of its com­mand line ar­gu­ments, pro­vided that they have valid nu­meric val­ues. As you show in hw.kt and userIn­put.kt, the main() func­tion takes one ar­gu­ment named args that’s an ar­ray of string vari­ables. These are the com­mand line ar­gu­ments of your pro­gram and are au­to­mat­i­cally as­signed by the com­piler, which is also the case in the ma­jor­ity of pro­gram­ming lan­guages.

The name of the next pro­gram is args.kt and con­tains the fol­low­ing sam­ple of Kotlin code: fun main(args: Ar­ray<String>) { if (args.size == 0) { println("Please give me at least one ar­gu­ment!") re­turn } println("1st ar­gu­ment: ${args[0]}!") for (k in args)

println("$k") }

The first thing this pro­gram does is make sure that it’s given at least one com­mand line ar­gu­ment. Fail­ing to test this might make your pro­gram crash.

You can also see here how you can ac­cess ar­ray el­e­ments in Kotlin: the first ele­ment of the args ar­ray can be ac­cessed as args[0] , the sec­ond as args[1] , and so on.

How­ever, args.kt re­veals an ad­di­tional method of ac­cess­ing the com­mand line ar­gu­ments of your pro­gram – the sec­ond tech­nique uses a for loop and won’t crash if there aren’t enough com­mand line ar­gu­ments. Nev­er­the­less, if you want to process a par­tic­u­lar com­mand line ar­gu­ment, it makes more sense to ac­cess it di­rectly.

Com­pil­ing and ex­e­cut­ing args.kt will cre­ate the fol­low­ing kind of out­put: $ kotlinc args.kt -in­clude-run­time -d args.jar $ java -jar args.jar Please give me at least one ar­gu­ment! $ java -jar args.jar 1 2 1st ar­gu­ment: 1! 1 2

It’s now time to see the Kotlin code of the pro­gram that finds the sum of its com­mand line ar­gu­ments – this is pre­sented in Fig­ure 5 ( aboveright). If you un­der­stand the code of args.kt, then you’ll have no prob­lem grasp­ing the ideas be­hind the code of sumArgs.kt.

Please note that the toInt() func­tion con­verts a string that rep­re­sents an in­te­ger to an ac­tual in­te­ger value – in this case toInt() is used to con­vert the com­mand line ar­gu­ments of

sumArgs.kt to their in­te­ger val­ues. Al­though Kotlin has ex­cep­tion han­dling ca­pa­bil­i­ties that are sim­i­lar to Java, the rel­e­vant code was omit­ted here for rea­sons of sim­plic­ity and code clar­ity.

Com­pil­ing and ex­e­cut­ing sumArgs.kt will gen­er­ate the fol­low­ing type of out­put: $ kotlinc sumArgs.kt -in­clude-run­time -d sumArgs.jar $ java -jar sumArgs.jar 1 2 3 4 5 Sum: 15

Func­tions in

In this sec­tion you’re go­ing to learn some ba­sic things about Kotlin func­tions. The func­tion that’s go­ing to be im­ple­mented here will cal­cu­late nat­u­ral num­bers that be­long to the well­known Fi­bonacci se­quence. The name of the Kotlin pro­gram will be fibo.kt and the im­ple­men­ta­tion of the fibo() func­tion is the fol­low­ing: 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 al­ready know, func­tion def­i­ni­tions in Kotlin be­gin with the key­word ‘fun’. Ad­di­tion­ally, the type of the re­turn value of a Kotlin func­tion is de­fined us­ing a colon af­ter the func­tion. If a func­tion has noth­ing to re­turn, then you can put Unit as its re­turn type. How­ever, you’re also free to omit the re­turn type for such func­tions – that’s why the main() func­tion pre­sented in hw.kt has no re­turn type. There­fore, the next two func­tion dec­la­ra­tions are com­pletely equiv­a­lent: fun fibo(n: Int): Unit fun fibo(n: Int) If you com­pile and ex­e­cute fibo.kt you’ll pro­duce the fol­low­ing kind of out­put: $ kotlinc fibo.kt -in­clude-run­time -d fibo.jar $ java -jar fibo.jar 10 Fi­bonacci Se­quence: 0 --1 -- 1 -- 2 -- 3 -- 5 -- 8 -- 13 -- 21 -- 34 --

Kotlin func­tions can carry out many more things than the ones pre­sented here – wait un­til the Kotlin tu­to­rial of the next Lin­ux­For­mat is­sue to learn more!

Sooner rather than later, you’ll have to try Kotlin, you’ll start de­vel­op­ing sys­tems soft­ware and new An­droid ap­pli­ca­tions and maybe start rewrit­ing old ones in Kotlin so why not start learn­ing Kotlin to­day? And if you run into the odd dif­fi­culty, don’t worry. Lin­ux­For­mat is here to help! LXF

Fig­ure 1 shows the ini­tial screen of the of­fi­cial Kotlin web site, which you should reg­u­larly visit to get in­for­ma­tion on the lat­est up­dates about the pro­gram­ming lan­guage.

Our ex­pert

Mi­halis Tsouka­los is a UNIX ad­min­is­tra­tor, a pro­gram­mer, a DBA and a math­e­ma­ti­cian who en­joys writ­ing ar­ti­cles and learn­ing new things in life.

Fig­ure 2 shows a small in­ter­ac­tion with the Kotlin REPL, which is an in­ter­ac­tive Kotlin shell where you can try things with­out fear of break­ing any­thing!

Fig­ure 3 uses the Kotlin REPL to il­lus­trate Kotlin mu­ta­ble and im­mutable vari­ables as well as Kotlin ar­rays.

Fig­ure 4 dis­plays the Kotlin code of userIn­put.kt, which is a pro­gram that reads two in­te­gers and cal­cu­lates the smaller in­te­ger of the two.

Fig­ure 5 demon­strates the Kotlin code of sumArgs.kt, which is a pro­gram that finds the sum of its in­te­ger com­mand line ar­gu­ments.

Newspapers in English

Newspapers from Australia

© PressReader. All rights reserved.