Kotlin Introduction

by "Blag" - Senior Developer Evangelist

Return to Geeky Thursday

What is Kotlin?


Kotlin is a statically-typed programming language that runs on the Java Virtual Machine and can be compiled to JavaScript source code.


It was developed by JetBrain in Saint Petersburg, Russia.


kotlin is free and Open Source.


While the syntax is not compatible with Java, is designed to interoperate with Java code and is reliant on Java code from the existing Java Class Library.

How to install Kotlin?


On Linux...download it from here, extract it and add the bin directory to the system path.

On my machine is on ~/kotlin/dist/kotlinc/bin


On Mac you do install it using Homebrew

brew update

brew install kotlin


On Windows, should be almost the same as Linux, as the bin folder contains the scripts to compile and run Kotlin

Who uses Kotlin?


  • JetBrains -> They created it...and use it for Interllij plugins, YouTrack vNext, CRM Apps.
  • Prezi.com -> Backend, data processing and service development.
  • GMC -> New Vertical Product with a team of 5 people.
  • 3D Robotics -> 3DR Tower Android App, source drone flight control app.

Starting out...


Once Kotlin is "installed", we can simply call it from the terminal

In my case...I needed to create a symbolic link as follows...

ln -s ~/kotlin/dist/kotlinc/bin/./kotlinc kotlinc

Basic Concepts


One line comments are // and multiple lines comments are /* and */.


Precedence must be enforced by parenthesis


				
println(2*3+5)

11


println(2*(3+5))

16
				

Basic Concepts


Printing on the screen is easy...


				
var text: String = "This is kotlin!"



println(text) 



This is kotlin!
				

Variables can be declared as mutable or immutable


				
var myNumber: Int = 5


myNumber = 10


println(myNumber)


10



val myNumber: Int = 5


myNumber = 10


java.lang.IllegalAccessError: 

tried to access field Line5.myNumber from class Line6 
				

Kotlin provides String Templates...which are really cool...


				
val first: String = "Hello"


val second: String = "World!"



println("$first $second")



Hello World!
				

Arrays


Arrays in Kotlin are not dynamic, so we need to specify its length

				
var myArray = arrayofNulls<String>(3)


myArray[0] = "A"

myArray[1] = "B"

myArray[2] = "C



(for i in myArray)
	
    println(i)
	
	
A

B

C
				

Or we can do it in the old fashioned way...

				
var myArray = arrayOf("A", "B", "C")


(for i in myArray)
	
    println(i)
	
	
A

B

C
				

Maps


Maps are like associate arrays or hashmaps in other languages...

				
val myMap = mapOf(1 to "A", 2 to "B", 3 to "C")


for((k, v) in myMap)


    prinln("$k --> $v")
    

    
1 --> A


2 --> B


3 --> C    
				

Functions

Functions must always return a value...

And function parameters are always immutable...


				
fun Hello(name: String): String{
	
	return("Hello " + name)
	
}



println(Hello("Blag"))


Hello Blag
				

Callable Functions

We can call a function as a parameter of another function

				
fun add(a: Int, b: Int): Int = a + b

fun multi(a:Int, b: Int): Int = a * b



fun operation(a: Int,b: Int,func:(a:Int,b:Int)->Int){

    val result = func(a, b)

    println("$result")

}



fun main(args: Array<String>) {

    operation(10, 10, ::add)

    operation(10, 10, ::multi)

}
				

Fibonacci List


Finally...we're going to make our first application...


So grab your favorite text editor and get ready...


Name your file "Fibonacci.kt"


				
package Fibonacci



fun fib(num: Int, a: Int, b: Int): String {

    var result: String = ""

    if(a > 0 && num > 1) {

        result = result + (a+b) + " " + 
        
        fib(num-1,a+b,a)

    }else if (a == 0) {

        result = a.toString() + " " + b + " " + 
        
        (a+b) + " " + fib(num-1,a+b,b)

    }

    return result

}
			
				
fun main(args: Array<String>) {

    if (args.size == 0) {

      println("Please provide a number...")

      return

   }

   val num: Int = args[0].toInt()

   println(fib(num,0,1))

}
				

Open the Terminal and go to your source code folder...

For some reason my symbolic link doesn't work...so I need to call the full route...

~/kotlin/dist/kotlinc/bin/./kotlinc fibonacci.kt -include-runtime -d "fibonacci.jar"

This will compile the app into a jar file

When we run it we're going to see...

Making an LED Number App


This is one of my favorite codes of all time...


Name your file "LED_Numbers.kt"


				
package LEDNumbers



fun main(args: Array<String>) {

    if (args.size == 0) {

      println("Please provide a number...")

      return

    }

    val NumList:List<String> = args[0].split("")
				
				

val Leds = mapOf("0" to listOf(" _  ","| | ","|_| "), 

                 "1" to listOf("  ","| ","| "),

                 "2" to listOf(" _  "," _| ","|_  "),

                 "3" to listOf("_  ","_| ","_| "),

                 "4" to listOf("    ","|_| ","  | "),

                 "5" to listOf(" _  ","|_  "," _| "),

                 "6" to listOf(" _  ","|_  ","|_| "),

                 "7" to listOf("_   "," |  "," |  "),

                 "8" to listOf(" _  ","|_| ","|_| "),

                 "9" to listOf(" _  ","|_| "," _| "))
				
				
    for(i in 0..2){

        for(j in 1..NumList.size - 2){

            print(Leds[NumList[j]]!![i])

        }

        print("\n")

    }                 

}
				

When we run it we're going to see...


Random Names


This App will generate 100,000 random names using two 16 elements arrays


We will measure the runtime


Name your file "Random_Names.kt"


				
package Random_Names



import java.util.Random



fun main(args: Array<String>) {

    val names = arrayOf("Anne","Gigi","Blag",
    
                        "Juergen","Marek","Ingo",

                        "Lars","Julia","Danielle",
                        
                        "Rocky","Julien","Uwe",
                        
                        "Myles","Mike","Steven",
                        
                        "Fanny")                  
				
				
    val last_names = arrayOf("Hardy","Read","Tejada",
    
                             "Schmerder",
                             
                             "Kowalkiewicz",
                             
                             "Sauerzapf","Karg",
                             
                             "Satsuta","Keene",
                             
                             "Ongkowidjojo",

                             "Vayssiere","Kylau",
                             
                             "Fenlon","Flynn",
                             
                             "Taylor","Tan")
			
				
    var full_names = Array(100000,{i -> i.toString()})

    val r = Random()

    for(i in 0..99999){

        var x = r.nextInt(16)

        var y = r.nextInt(16)

        full_names[i] = names[x] + " " + 
        
                        last_names[y]

    }

}
			

When we run it we're going to see...

How this behaves in Python?

And in Julia?

Decimal to Romans


This App will create a Roman Numeral based on a decimal number


This will include some nice commands...


Name your file "Decimal_to_Roman.kt"


				
package Decimal_To_Roman



fun roman_number(num: Int, Romans: 
                 
                 Array<Pair<Int,String>>, 
                 
                 Counter: Int, result: String){

    val roman = Romans[Counter].first

    if(num >= roman){

        roman_number(num-roman,Romans,Counter,
        
                     result+Romans[Counter].second)

    }else if (num < roman && num > 0){

        roman_number(num,Romans,Counter+1,result)

    }else if (num <= 0){

        println(result)

    }

}
			
				
fun main(args: Array<String<) {

   if (args.size == 0) {

      println("Please provide a number...")

      return

   }

    val num: Int = args[0].toInt()

    val Romans = arrayOf(Pair(1000,"M"),Pair(900,"CM"),

                         Pair(500,"D"),Pair(400,"CD"),

                         Pair(100,"C"),Pair(90,"CX"),

                         Pair(50,"L"),Pair(40,"XL"),

                         Pair(10,"X"),Pair(9,"IX"),

                         Pair(5,"V"),Pair(4,"IV"),

                         Pair(1,"I"))

    roman_number(num, Romans, 0, "")

}
			

When we run it we're going to see...


Count Letters


In this example we're going to read a file and count how many time a letter appears...


Call your file "countletters.kt" (all in lowercase).


Create a file called "readme.txt" with the following text...


"This is a text file that we're going to read it using Kotlin"


				
package countletters



import java.io.File



fun main(args: Array<String>) {

    val line = File("readme.txt").readText(
    
               charset = Charsets.UTF_8)

    val len = line.length

    var letters = arrayListOf(Pair("",0))

    letters.remove(Pair("",0))

    var flag: Boolean
			
				
for(i in 0..len - 1){

    flag = false

    if(letters.size > 0){

        for(j in 0..letters.size - 1){

            if(letters[j].first==line[i].toString()){

               letters.set(j,Pair(line[i].toString(),
               
                           letters[j].second + 1))

               flag = true

               break

            }

        }

        if(flag == false){

            letters.add(Pair(line[i].toString(),1))

        }
			
				
       }else{

            letters.add(Pair(line[i].toString(),1))

       }

    }

}
			

When we run it we're going to see...


That's it for now


kotlin is a nice and interesting language


Sadly, there's not much documentation or books around it...


Contact Information


Blag --> blag@blagarts.com

@Blag on Twitter

Go back home...