Kotlin Basics Part Two

 Kotlin logo

Introduction

    This is the second part of Kotlin Basics. The first part was about Basic types, Operators, Conditions, Variables and Nullability. You can check it here.  In this article, I will talk about Strings, Boolean data Types, Boolean Operators, Lists, Arrays, Lists VS arrays and finally Loops. A quiz will be included at the end of the article, as this will give an indication of whether you have absorbed the concepts covered here or not. As I said before, You don't have memorise the syntax, as you can check for any cheat sheets. 

To practice Kotlin

A girl sitting on a chair with a laptop illustration
  1. Open Android studio
  2. Choose a new Empty Activity > Next > Name the project > Choose Kotlin Language > Finish
  3. Click on tools  > Kotlin > Kotlin REPL
  4. The REPL will appear in the window's bottom
  5. Press Ctrl + Enter to execute any code

Strings in Kotlin

    Strings in Kotlin are pretty much the same as in any other languages. Check the following code for the features:


//Concatenation 

val firstName = "Leila"

val lastName = "Kim"

firstName  + lastName

res0: kotlin.String = LeilaKim

"Leila" + "Kim"

res1: kotlin.String = LeilaKim


//Building a String and Replacing text by its value using the dollar sign

"My name is $firstName"

res2: kotlin.String = My name is Leila


//We can use any type even an Integer

val age = 20

"$firstName is $age years old."

res3: kotlin.String = Leila is 20 years old.


//Integers can get added first before being displayed in the result

val brother = 1

val sister = 1 

"$firstName has ${brother + sister} siblings"

res4: kotlin.String = Leila has 2 siblings

Boolean data types And Boolean Operators in Kotlin

    Kotlin has Boolean data types just like other languages. Its value can either be true or false. 

// A variable of type Boolean with value true

val isEmpty: Boolean = true

// A variable of type Boolean with value false

val isFull: Boolean = false

    Boolean Operators are logical equality operators to compare between two values, and the result would be a boolean value of either true or false.There are logical boolean operators used with conditions to make the program flow control logic. Check the examples below:


//Two variables of value 21 and 18

val leilaAge = 21

val sisterAge = 18


//Equal comparison "use a double equal sign"

//Is 21 equal to 18? No, so the output is false

leilaAge == sisterAge

res0: kotlin.Boolean = false


//Not equal comparison

//Is 21 not equal to 18? Yes, so the output is true

leilaAge != sisterAge

res2: kotlin.Boolean = true


//Greater than comparison

leilaAge >  sisterAge

res3: kotlin.Boolean = true


//Greater than or equal comparison

leilaAge >= sisterAge

res4: kotlin.Boolean = true


//Less than comparison

leilaAge < sisterAge

res5: kotlin.Boolean = false


//Less than or equal comparison

leilaAge <=sisterAge

res6: kotlin.Boolean = false

Conditions in Kotlin

    There are two basic ones in Kotlin, they are if-else and when. We can nest them as well, which means we can use if  then else if then else. So testing for conditions is as follows:

//If - else  statement 

// if the condition is true, the program executes a certain block of code, if the condition is false, the program executes the block of code after "else"

if(sisterAge>=16) println("she can drive")

 else println("She can not drive ")

Output: she can drive

 

//Kotlin lets use range of values inside the condition

if(sisterAge in 13..19) println("Still a teenager")

Output: Still a teenager

 

//when is like switch for other languages

when(sisterAge){

     6 -> println("A child")

     18 -> println("A teenager")

     21 -> println("An adult")

 }

Output: A teenager


Lists in Kotlin

    There are two types, List<T> and MutableList<T>. List<T> has objects with specified order while MutableList<T> has objects where we can add or remove elements from inside the list. As follows:

//A list of elements of type integer

val numbers:List<Int>  = listOf(1,2,3,4)

println("The size of the list is ${numbers.size}")

The size of the list is 4

println("The first element is ${numbers.get(0)}")

The first element is 1


//A mutable list of elemets of type integers

val mutableNumbers:MutableList<Int> = mutableListOf(1,2,3,4)

 println("The size of the list is ${mutableNumbers.size}")

The size of the list is 4

println(mutableNumbers.add(0,0))

kotlin.Unit

println(mutableNumbers)

[0, 1, 2, 3, 4]

mutableNumbers.removeAt(4)

res0: kotlin.Int = 4

println(mutableNumbers)

[0, 1, 2, 3]


Arrays in Kotlin

    We can create an array using arrayOf(). There are primitives type arrays as well: ByteArray, ShortArray & IntArray. As the name suggests, They are for byte, short & Int data types, respectively. Few Examples below: 


//An array of Strings

val movies = arrayOf("Harry Potter", "Lord of the rings", "star wars")

//We can make an array of mixed data types

val mixedArray = arrayOf("Harry Potter", 8)

//We can nest arrays so we have an array of arrays, When we print it, we can not really see the elements inside the Array as follows:

val nestedArray = arrayOf(movies, arrayOf(1,2,3))

println(Arrays.toString(nestedArray))

[[Ljava.lang.String;@7be677a6, [Ljava.lang.Integer;@580901ca]

//An int array

val numbers: IntArray = intArrayOf(1,2,3)

//An int array of size 7 with values [0,0,0,0,0,0,0]

val zeroArray = IntArray(7)

//An int array of size 6 with values [5,5,5,5,5,5]

val arrayOfFive = IntArray(6){5}

//An int array of size 6 with its values equal to their index value

var arrayOfIndex = IntArray(6){it*1}


    Printing  an array or accessing its elements is a bit tricky. To print an array:

///First way to print an array

Arrays.toString(zeroArray)

res0: kotlin.String! = [0, 0, 0, 0, 0, 0, 0]

Arrays.toString(arrayOfFive)

res1: kotlin.String! = [5, 5, 5, 5, 5, 5]

Arrays.toString(arrayOfIndex)

res2: kotlin.String! = [0, 1, 2, 3, 4, 5]

//Another way to print an array "Note: Loops will be explained later in this Article"

for(element in arrayOfIndex){

     println(element)

 }

012345

//Third way to print an array

arrayOfIndex.forEach { println(it) }

012345

//A Fourth way to print an array

println(arrayOfIndex.asList())

[0, 1, 2, 3, 4, 5]


Arrays Vs Lists in Kotlin

    
Arrays are mutable.  They have fixed size, so we can't  add or remove items. This means we  can change the value of the elements inside an array without changing its size

Lists are immutable, unless we  are using mutableList. With mutableList we can add or remove items.
Check the code below: 

//Changing the value of the first element in an array

//Before

var arrayOfIndex = IntArray(6){it*1}

println(arrayOfIndex.asList())

[0, 1, 2, 3, 4, 5]

//After

arrayOfIndex[0] = 1

println(arrayOfIndex.asList())

[1, 1, 2, 3, 4, 5]

//Trying to Change the value of the first element in a list

val numbers:List<Int>  = listOf(1,2,3,4)

numbers[0] = 2

error: unresolved reference. 


Loops in Kotlin

    Loops are like every other programming languages, we can iterate over an iterable object. As follows:

//Looping over the index and elements at the same time

//withIndex() make an object iterable that contains the index of the element and its value

for ((index, element) in movies.withIndex()){

     println("Movie at $index is $element ")

 }

Movie at 0 is Harry Potter Movie at 1 is Lord of the rings Movie at 2 is star wars 

//Looping over ranges of different types

//Looping over range of alphabets, be careful to use a single quotations for a character instead of double quotations that is used for a string

for(e in 'a'..'d') println(e)

abcd

//Looping over range of numbers

for(e in 2..8) println(e)

2345678

//Looping over numbers going downward

for(e in 9 downTo 0 ) println(e)

9876543210

//Looping over numbers with different step

for(e in 2..8 step 2) println(e)

2468

     
    This is how While loop works: as long as the condition is true, a block of code would be executed. While loop has continue and break with an ability to referencing and labeling the loop using @ symbol. Continue is for skipping a loop and break is for stopping the loop.

var Timer = 20

 while (Timer>0){

     println(Timer)

     Timer--

 }

2019181716151413121110987654321

QuizA book with right and wrong illustartion

1. What is the output for this line of code: 

     val mutableNumbers = mutableListOf("one", "two", "three", "four")

      println(mutableNumbers[1])

 
 

2. What is the output of this code: 

    val numbers  = listOf("one", "two", "three", "four")

     println(numbers.indexOf("three"))
    

 
 

3. Val array = //array initialization here 

 val movies = arrayOf("Harry Potter and the Philosopher's stone", "Harry Potter and the Chamber of Secrets", "Harry Potter and the Prisoner of Azkaban","Harry Potter and the Goblet of Fire", "Harry Potter and the Order of the Phoenix", "Harry Potter and the Half-Blood Prince", "Harry Potter and the Deathly Hallows part 1", "Harry Potter and the Deathly Hallows part 2")

 for ((i, value) in array.withIndex()) {

     println(" ${movies[i]} is movie number ${value.toString()} ")
     println(" \n")
 }

Which array initialization will generate the following output ?

 Harry Potter and the Philosopher's stone is movie number 1  
 Harry Potter and the Chamber of Secrets is movie number 2  
 Harry Potter and the Prisoner of Azkaban is movie number 3  
 Harry Potter and the Goblet of Fire is movie number 4  
 Harry Potter and the Order of the Phoenix is movie number 5  
 Harry Potter and the Half-Blood Prince is movie number 6  
 Harry Potter and the Deathly Hallows part 1 is movie number 7  
 Harry Potter and the Deathly Hallows part 2 is movie number 8 
    


4. What is the output of this code: 

    var hotelLevel = 1

    when(hotelLevel) {

         0 -> println("Lobby")
         in 1..9 -> println("Rooms floors")
         10 -> println("Roof")
         else -> println("Not inside the Hotel")

     }

 
 
 
 


    Thank you for reading my post. You can subscribe to my blog or follow me on Twitter to be the first person to read my new posts.

0 Comments