Kotlin In a Nutshell Part 1

Kotlin In a Nutshell Part 1

Get up and running with Kotlin in no time


Baraa Abuzaid
Baraa Abuzaid
@baraaabuzaid
Kotlin In a Nutshell Part 1

If you like me you probably have heard of Kotlin, but you have been resisting its temptation.
I kinda of understand that. You have all of those shiny cross-platforms framworks to learn Xamarin, React Native and Flutter …
And if you are already android dev I know what you probably thinking. and it goes something along the line of

” if I have the time why on earth should I learn another way of doing the same thing while I could rock both platforms by investing the same amount of time learning something like Dart”.

I could totally relate to that because I have been there too. But,rest assured that learning Kotlin won’t be brain and time intensive operation as learning Dart-Flutter or Xamarin. Not to mention, all those shiny cross platforms development frameworks once you embark on one of them they’ll required you to learn a whole lot of new tools. From how to deal with network call to how to parse JSON. Eventually, you’ll start missing libraries like Retrofit Dagger and what have you…
However, this is not what I intended from this article, drawing another boring comparison between learning Kotlin VS Dart. My aim here is to go through Kotlin in a very time effective way and let you make the decision yourself. Meanwhile, through the article, I’ll annotate my favorite feature with hashtag #That_alone_will_make_you_switch

1st Kotlin val VS var

At the beginning, you might notice “val”, “var” keyword. “val” is indicating the variable is immutable once its been initialized can’t be changed. And “var” for your typical mutable variable. And not like Java. In Kotlin, we declare the type at the end after a colon. However, type declaration is optional as it could be inferred.

    var books:Int = 0
    val mathBooks:Int = 71
    val historyBooks:Int = 233
    books += mathBooks+ historyBooks
    books -=13

    val booksPerShelf:Int = books/4;

    println("book per shelf : "+booksPerShelf);

 

2nd Kotlin String template & Nullable type R.I.P. NullPointerException

#That_alone_will_make_you_switch
Kotlin support string template. In addition to nullable type. that allows us to check the for nullability and potentially avoid null pointer exception.
so if you would like to make an object null you have to declare it as nullable type first by the suffix “?”.

As you might notice semicolon is optional

val banana = "banana"
val apple = "apple"
val orange = "orange"
println("I like to drink ${apple} and $orange juice early in the morning")

so the line greenColor?.length won’t rise a null pointer exception even if greenColor is null.

// declaring a nullable type
var greenColor:String? = null   
println("length ${greenColor?.length}  is null  ${greenColor.isNullOrEmpty()} ")

 

3rd Kotlin List

I could declare a list that contain a nullable type or any other type like. val mList:List<Int?> = listOf(null,null,null) However, the list itself could be a nullable type. val myList:List<Int>? = null. Moreover, Kotlin has what it called an Elvis operator, it allows the check for nullability and doing an operation like increment Integer if it is not null or set back to zero if it is null, all in one line.

// list contains nullable objects 
val mList:List<Int?> = listOf(null,null,null)
println("List size ::"+mList.size)

// nullable list 
val myList:List<Int>? = null
println(myList?.get(0))
 
// Elvis operator
var nullTestNumber:Int? = null;
println(nullTestNumber?.inc() ?: 0)

The above list created by listOf() is immutable list, and can’t be modified once it is been created. however, to create a mutable list you must use MutableList<Int> type.

var list3 : MutableList<Int> = mutableListOf()
    for (i in 0..10 step 2){
        list3.add(i)
    }
    print(list3)

4th kotlin for loop and the amzing “In” operator

For loop is also different in Kotlin with the addition of the very powerful
in operator. Instead of using the old school for loop, in kotlin you could use for with a combination of in operator. looping in range from 0 to 10 could be done as for (i in 0..10){...} and you could even spice it up by adding a step to increment with define step size. for (i in 0..10 step 2){...}

var list3 : MutableList<Int> = mutableListOf()
    for (i in 0..10){
        list3.add(i)
    }

print(list3)

Meanwhile, if you would like to have an access to the index while looping, no need to have an additional variable you could easily do it by calling the method  withIndex()

var arr = listOf<String>("jone","mike","steve","Doe")
    for ((index,name) in arr.withIndex()){
        println(">> $index : $name")
    }

#That_alone_will_make_you_switch
and you could even loop in a range. so for (i in 'a'..'g') print(i) will loop over the letters in a range from a to g.

for (i in 'a'..'g') print(i)
for ( i in 7 downTo 1  step 2) print(i)
for (i in 1..9 step 3) print(i)

furthermore a combination of in operator with if statement could be used to decide the existence of an element in a list.

val listRange = listOf<String>("mike","ali","jone")
    if ("BARAA".toLowerCase() in listRange)
        println("Ok >> member in list");
    else
        print("No >> member is not in the list");

and in a similar fashion to the list, the array in kotlin could be initialized and populated with easy. If you find the syntax to be wired I’ll explain more on that in the next tutorial.

val sizes = arrayOf("byte", "kilobyte", "megabyte", "gigabyte",
            "terabyte", "petabyte", "exabyte");

val mArray = Array(10){it *2};
println(mArray.asList());

 

5th kotlin control flow statement with “when” 

Kotlin has a nice replacement to switch..case and that’s when statement. But not like switch..case, when doesn’t require you to end every block with break, and it actually returns a value. in fact, all Kotlin statement does return value. In addition you could combine when with in-clause to have a powerful control flow.

   var welcomeMessage = "Hello and welcome to Kotlin"
    when(welcomeMessage.length){
        0 -> println("it's empty")
        in 1..50 -> println("within the range")
        else -> println("it's lengthy!")
    }

    val dayNum = 6
    var dayStr:String  = when(dayNum){
        6 -> "Saturday WoOw it's a holiday"
        7 -> "Sunday WoOw it's a holiday"
        else -> "just a working day!"
    }
    println(dayStr) // output:  Saturday WoOw it's a holiday

 

In the upcoming blogs we’ll discuss more about kotlin, covering kotlin function,classes,extention method,lambda and more…

 

featured photo by Elijah O’Donell

Show Comments (0)

Comments

Related Articles

A Complete Guide To Design Patterns In Kotlin: Composite Design Pattern
Kotlin

A Complete Guide To Design Patterns In Kotlin: Composite Design Pattern

A composite design pattern is built upon two principles in object-oriented programming. First, decomposition by breaking a whole into parts. Then generalization which generalizing...

Posted on by Baraa Abuzaid
Why Kotlin Favor Composition Over Inheritance
Kotlin

Why Kotlin Favor Composition Over Inheritance

For starters what is composition and what is inheritance? A simple way to explain that is to say the Composition is when you design your object around what they do, and the...

Posted on by Baraa Abuzaid