MODULE ONE: INTRODUCTION TO KOTLIN PROGRAMMING 101.

dbriane208

Daniel Brian

Posted on March 26, 2023

MODULE ONE: INTRODUCTION TO KOTLIN PROGRAMMING 101.

Hellooooo🥳️🥳️🥳️I am glad🤗 that you have joined me again in this Android development journey🚀. I am glad that you have decide to join me again on this exciting journey as we explore the world of kotlin for Android development. Here is one of the three articles we will be interacting with🥳️🥳️.Do not forget to 👍like, comment👍 and share with your friends👨‍👨‍👦‍👦🥳️.

Before we start here is a great saying by the Kotlin inventor:

"I wanted a better language than Java, so I started experimenting with one which could run on a JVM but which would be less syntactically verbose, more expressive, and which would remove some of the error-proneness of the Java type system. The result of this experimentation was the Kotlin programming language."
JetBrains co-founder and Kotlin inventor, Andrey Breslav.

  • Programming is a fascinating scale that allows you to talk to computers.
  • A program is simply a set of instructions created using a programming language that a computer must follow.
  • A programming language is a little like a bridge that we use to talk to computers and people.
  • Programming languages are classified into levels;

    i. Low-level programming language: This is a machine language with zeros and ones. It is clear to be understood by a computer CPU.

    ii. High-level programming language: This language needs to be interpreted that is converted to binary code that a CPU will be able to work with.

  • Kotlin is one of the high-level languages that need to be interpreted. Since its announcement by Google as the official language for developing android native apps, Kotlin has gained and continues to gain popularity in the field over the previously used Java programming language.
    Imagekvj

  • Some of the reasons Kotlin is preferred over Java include :
    1.It is concise and standardized hence low code errors.
    2.Easier to maintain complex projects due to low code.
    3.It is compatible with java hence easy to convert java
    code to Kotlin.
    4.Kotlin handles errors that crash Android apps better
    than java.

  • In addition, you might be wondering what else Kotlin could do apart from developing Android apps. Here are some of the fields Kotlin is gaining popularity :

Back-end web development: modern features that have been
added to kotlin have enabled the language to be used on
the server side since applications can scale quickly.
Kotlin also uses Spring frameworks used in java which
makes it easy for developers to work well with it.

kotr

Full-stack web development: Kotlin/JS allows developers to
access powerful browsers and web APIs in a type-safe
fashion. They can write front-end code in the same language
that they used for back-end code, and it’ll be compiled
into JavaScript to run in the browser.

full stack

  1. Data Science: Data Scientists have always used Java to crunch numbers, detect trends, and make predictions — so it only makes sense that Kotlin would find a home in data science as well.

data

  1. Multi-platform mobile development: In the coming future one Kotlin code base would be used to compile and run apps not only in Android but also in iPhones and Apple watches. This project is currently in the alpha testing stage.

km icon

In this module, we will cover the following objectives :

  1. Variables, values, and type in kotlin
  2. Numbers in kotlin
  3. Using texts in kotlin
  4. Boolean values and Operations
  5. Conditional statements in Kotlin.
  6. Loops in Kotlin

1.Variables, values, and type in kotlin

  • Variables are containers used to store data values in Kotlin. Variables can change the values that it stores. They are abbreviated as var. Variables can be reassigned.
fun main (){
    //Ok! val cannot be reassigned
   var name = "John"
   name = "Sharon"
              }
Enter fullscreen mode Exit fullscreen mode
  • Val is an abbreviation of value. You can use this modifier to specialize variables that cannot be changed. In other words code will not start if you try to assign new value.
fun main (){
    //Error! val cannot be reassigned
   val name = "John"
   name = "Sharon"
              }
Enter fullscreen mode Exit fullscreen mode
  • Values are grouped into types:

i. Strings - represent values in texts. eg mountain
ii. Integer - represents real numbers. eg 56
iii. Double - represents numbers with decimal places. eg 45.0
iv. Boolean - represents a true or a false value. eg 5 == 6 is false

  • Some of the reasons we explicitly use val

    1. Val is used for readability such that the reader can understand the written code.
    2. With val it is enough to view its declaration to know which value it is.
    3. Val minimizes the number of unnecessary variable changes which increases the readability of your code.

           fun main () {
           val age : String = "" + 42 + ""
             }
      
  • There are a few reasons to use the explicit variable type. One is readability. Sometimes the right side of the assignment might be complicated and specifying a type to makes it easier to understand your code.

    fun main () {
    var x : Any = "ABC"
    println(x) // ABC
    x = 123
    println(X) // 123
    x = true
    println(x) // true
               }
    
  • One of the reasons you specify type is when you need a value to include multiple subtypes.

  • For instance Any is a data type that includes all other types. So String, Int, and Boolean are all subtypes of Any. With the type of Any, you can assign it any value you've learned about so far.

2. Numbers in Kotlin

  • There are four basic types of operations used in kotlin which include :
    i.Int
    ii. Float
    iii.Double
    iv. Long

  • Integer: it represents real whole numbers that can either be positive or negative. We add a minus sign in front of an integer to make it negative. Integers have a limited size of over two billion.

  • Long: represents a number type that can accommodate numbers over nine quintillions to create a long value. We add a suffix L after the number.

  • Double: It contains a number that operates with a decimal part. It holds a number made up of two parts. It contains the integer part and a decimal. It can hold up to 15 to 16 decimal places. A double is more precise than a float. This is because a double occupies twice memory as an integer.

  • Float: It holds up to 7 to 8 decimal places. We create this number by using the suffix F after the number.

  • Kotlin can be used to can be used for basic math operations. eg

 println(1+3*2) output = 7
 println((1+3)*2) output = 8
Enter fullscreen mode Exit fullscreen mode
  • Parenthesis are used to override the normal math precedents to create a particular calculation.
  • Transformational functions are used to transform one number type to another. We use the to prefix and the type you want. eg
 fun main () {
val num1 : Int = 10
val num2 : Long = num1.toLong()
val num3 : Double = num2.toDouble()
val num4 : String = num3.toString()
val num5 : Float = num3.toFloat()
println(num1)
println(num2)
println(num3)
println(num4)
println(num5)
              }
Enter fullscreen mode Exit fullscreen mode
  1. The output of the first print statement is 10
  2. The output of the second print statement is 10
  3. The output of the third print statement is 10.0
  4. The output of the fourth print statement is 10.0
  5. The output of the fifth print statement is 10.0
  • In kotlin, the remainder operation is represented by a modulus sign(%). It represents what would be left if you divide an integer by another integer.
 fun main () {
println(10%3)// 1
println(12%4)// 0
println(17%5)// 2
// The sign of the result is always the same as the sign of the left side.
println(-1%3) // -1
println(1%-3) // 1
println(-1%-3) // -1
}
Enter fullscreen mode Exit fullscreen mode
  • When you carry out operations between;

Integer and Integer the result will be an Integer
Integer and Long the result will be a Long
Decimal and Integer or Decimal the result will be an
Decimal
Float and Integer the result will be an Float
Float and Double the result will be an Double

  • Division operation between two integers results into an integer. If the calculation results in a decimal part of this operation is lost.
  • To ensure fractions are retained, transform one of the values to a double or float before the math operation.
 fun main () {
       val a = 5
       val b = 2
       println(a/b)
       println(a.toDouble()/b)
              }
Enter fullscreen mode Exit fullscreen mode
  1. The output of the first print is 2
  2. The output of the second print is 2.5

Augmented Assignment

  • Variables defined with var can have their value changed.
fun main () {
var num = 10
println(num)
//reassigning num
num = 20
println(num)
}
Enter fullscreen mode Exit fullscreen mode

The output of the first print is 10
The output of the second print is 20

  • We can also increase value through different operations. Instead of using a = a + b we can use a += b. This implies to all the other operations that we increment by using the operation sign next to an equals sign.
fun main () {
var num = 10
num += 20
println(num)
num -= 5
println(num)
num *= 4
println(num)
num /= 50
println(num)
}
Enter fullscreen mode Exit fullscreen mode
  1. The output of the first print is 30 because we are adding 10 to our initial value which was 20 resulting in 30.
  2. The output of the second print is 25 because we are subtracting 5 from the result of the above operation which was 30 resulting in 25.
  3. The output of the third print is 100 because we are multiplying 4 by the result of the above operation which was 25 resulting in 100.
  4. The output of the fourth print is 2 because we are dividing 50 by the result of the above operation which was 100 resulting in 2.

Prefix and postfix operation

  • In Kotlin there are different ways to add and subtract. We can either use a postfix or a prefix to do an increment. In postfix, the execution is done after the operations are evaluated.
fun main () {
var a = 5
var num = 6 + a++
println(num)
}
Enter fullscreen mode Exit fullscreen mode

The output will be 11 because num takes the value of a and adds it before a++ increments 5 to 6.

  • In Prefix operation works differently. The prefix operation is executed before the equation is evaluated.
fun main () {
var a = 5
var num = 6 + ++a
println(num)
}
Enter fullscreen mode Exit fullscreen mode

The output will be 12 because a++ takes the value of a then add 1 to it such that now a++holds 6 as a value which is added to6 stored in the variable num.

3. Using texts in Kotlin

  • Char is an abbreviation of character. In kotlin character is defined by placing it inside a set of single quotes. var mychar : Char = 'a'
  • In programming characters are represented by numbers because a computer understands binary codes which are made up of zeros and ones.
  • Unicode is a special table that is used to map each character to a unique number. It supports 144,697 characters.
  • A string _is a sequence of characters. It can be empty or have one or more characters including spaces and commas. String value is specified through _double quotes. Strings are immutable.
  • If your text contains multiple lines, it is also possible to define this in a string variable in kotlin by delimiting the text with tripple quotes.
fun main () {
val myString = """Hello world! My name is Daniel Brian. 
I love android development with kotlin."""
println(myString)
}
Enter fullscreen mode Exit fullscreen mode

The output of the print statement is:
Hello world! My name is Daniel Brian.
I love android development with kotlin.

  • String has built-in code which can be used to access the information about them such as the keyword length. The length keyword is used to access the number of characters in a string.
fun main () {
val name = "Simpsonville"
println(name.length)
}
Enter fullscreen mode Exit fullscreen mode
  1. The output of the print is 12 showing that the string Simpsonville has 12 characters.
  2. String template allows you to include a variable in a string. To do this you use a dollar sign in the variable name.
fun main () {
val name = "Simpsonville"
val age = 20
println("My name is $name I am $age years old.")
}
Enter fullscreen mode Exit fullscreen mode

The output of the print statement is: My name is Simpsonville I am 20 years old.

  • When you use $(dollar sign) without brackets you only inline a variable value not the rest of an expression.
fun main () {
val num1 = 50
val num2 = 20
println(" $num1 + $num2 = ${num1 + num2}")
}  
Enter fullscreen mode Exit fullscreen mode

The output of the print statement is 50 + 20 = {num1 + num2} but after we put the dollar sign the output changes to 50 + 20 = 70

  • To convert a Char to a String using the toString() function.
fun main () {
val myChar = "H"
val myLongStrong = myChar.toString()
println(myLongStrong)
}
Enter fullscreen mode Exit fullscreen mode

The output is: H

Appending to string

  • To add additional text to the end of a string, we use the plus operator(+). This does not change the existing string variable but creates new string variable.
fun main () {
val name1 = "Google!!"
val name2 = "I love " + name1
println(name2)
}
Enter fullscreen mode Exit fullscreen mode

The output of the code is I love Google!!

Searching Strings

  • The string type has multiple functions for searching its content. We can search the first letters of a word or the last letters.
fun main () {
val name = "Google"
val startWithGo = name.startsWith("Go")
val endWithMe = name.endWithMe("me")
println(startWithGo)
println(endWithMe)
}
Enter fullscreen mode Exit fullscreen mode

The output of the first println is true because the name Google start with the character Go else the output will be false.
The output of the second println is false because the name Google doesn't end with the letters "me". It could be trueif the last letters indicated would be le

  • We can use variable name.first() to get the first character of a variable or variable name.last() to get the last character of a variable.
fun main () {
val name = "Google"
val nameIsFirst = name.first()
val nameIsLast = name.last()
println(nameIsFirst)
println(nameIsLast)
}
Enter fullscreen mode Exit fullscreen mode

The output of the code will be G and e respectively.

Manipulating Strings

  • We can use the uppercase and the lowercase methods to manipulate strings to capital letters and small letters.
fun main () {
val name = "Google"
val nameIsFirst = name.uppercase()
val nameIsLast = name.lowercase()
println(nameIsFirst)
println(nameIsLast)
}
Enter fullscreen mode Exit fullscreen mode

The output of the first println is GOOGLE while the output of the second println is google

  • We can also get the position of all the letters in string through the substring function.
fun main () {
val name = "Google"
val nameIsLast = name.substring(1)
println(nameIsLast)
}
Enter fullscreen mode Exit fullscreen mode

The output of the code above is oogle because the substring prints from the index referenced inside the function which is 1.

4. Boolean values and Operations

  • Boolean has two possible values true and false and can be used to tell whether something is true or not.
  • When you compare two values, the result is of either the == operator or the equals() when comparing strings.
fun main () {
val num = 45
val num1 = 56
val output = num.equals(num1)
println(output)
// when using the == operator
println(45 == 56)
} 
Enter fullscreen mode Exit fullscreen mode

The output of the above code is false because 45 is not equal to 56

  • To check if two values are not equal we can use exclamation mark and equals sign(!=)
fun main () {
// when using the != operator
println(45 != 56)
}  
Enter fullscreen mode Exit fullscreen mode
  • The output of the above code is true because 45 is not equal to 56
  • In addition we can use other operators such as the greater and the less than signs followed by an equal sign to check if certain numbers are equal or not.

Note: The output of the below code is given in boolean next to the println statement.

fun main () {
println(45 < 56) // true  
println(45 > 56) //false
println(45 <= 56) //true
println(45 >= 56) //false
}
Enter fullscreen mode Exit fullscreen mode

Logical operations : Boolean

The and operator (&&)

  • The and-operator returns true when the conditions given are both true else it returns false.

The or operator (||)

  • The or operator returns false when both of the conditions given are false else it returns true. The not operator(!)
  • It negates the boolean value. It turns true into false and false into true.
fun main () {
val isAmazing = true
println(!isAmazing)//false
val isBoring = false
println(!isBoring)//true
}
Enter fullscreen mode Exit fullscreen mode

The output of the above code is false for the first print statement and true for the second statement.

  • A good analogy for the logical operator not is a minus before a number. It turns a number into a positive and a positive to a negative.
fun main () {
val num = 1
println(-num)//-1
}
Enter fullscreen mode Exit fullscreen mode

The output is a negative integer -1

  • In programming, you can use negation multiple times. Even number of negations returns the boolean being negated while odd number of negations returns the opposite of the boolean provided.
fun main () {
println(!true)//false
println(!!true)//true
println(!!!true)//false
println(!!!!true)//true
}
Enter fullscreen mode Exit fullscreen mode

5. Conditions in Kotlin

If condition

  • The syntax for the if condition is

    if(condition){
    println(specify what to be printed)
    }

  • Every line in the body of a statement starts with four additional spaces known as indent and the whitespaces which improves code readability.

 fun main () {
val accountType = "free"
    if(accountType == "free")
    println("show adds")
}
Enter fullscreen mode Exit fullscreen mode

The output of the above code will be showing adds since the the condition is met.
If - else condition

  • An if-else statement can be used as an expression in other words, to return a value that can be stored in a variable. The returned value is the value returned by the body block that was chosen.
  • Inside if else bodies you can include more than one statement. The value returned by the body is the last expression it has.
fun main() {
    val accountMoney = true
    val tip: Double = if (accountMoney) {
        println("You can withdraw")
        89.0
        90.0
        100.0
    } else {
        println("Sorry, I am broke")
        0.0
    }
    println(tip)
}
Enter fullscreen mode Exit fullscreen mode

The output will be You can withdraw 100.0

If- else- if

  • It is a structure that checks condition one after the other until it finds the first one that is fulfilled, and calls its body.
  • It is not popular in Kotlin because there is better alternative, called the when statement.
fun main() {
 println("Is it going to rain?")
    val probability = 70
    if (probability <= 40) {
        println("Unlikely")

    } else if (probability <= 80){
        println("Likely")
             }
    else if(probability <100){
        println("Yes")
    }
   else{
       println("what?")
   } 
}

Enter fullscreen mode Exit fullscreen mode

The output of the code is likely

When condition statement

  • It starts with the keyword when then open the curly braces. Inside the curly braces, write a condition and the body that should be executed.

when {
condition -> {body to be executed}
condition -> {body to be executed}
else -> {body to be executed}
}

  • The when statement can be used as an expression inprder to produce a value. When statement must have an else block so that it can have something to return incase no other block is chosen.
fun main() {
    println("Is it going to rain?")
    val probability = 70
    val text = when{
        probability <= 40 -> "unlikely"
         probability <= 80 -> "unlikely"
         probability <= 100 -> "unlikely"
        else -> "what?"
    }
    println(text)
}
Enter fullscreen mode Exit fullscreen mode

The output of the above code is Unlikely.

  • If you add a value in brackets after the when keyword, then in each branch, kotlin compares this value to others.
fun main() {
    val number = 80
    when(number){
         70-> {println("missed hit") }
         80,90,100-> {println("Hit with value $number") }
         110-> {println("critical hit") }
    }
  }
Enter fullscreen mode Exit fullscreen mode

The output of the code is Hit with value 80

  • We can use the when statements with the range check. The syntax starts with the in keyword, and then specify either a collection or a range that might contain the value or not.
fun main() {
   val number = 99
   val text = when(number){
         70-> {println("missed hit") }
         in 80..100-> {println("Hit with value $number") }
         110-> {println("critical hit") }
         else -> "unsupported"
    }
  println(text)
}
Enter fullscreen mode Exit fullscreen mode

6. Loops in Kotlin

  • Loops allow the execution of one or more statements until a condition is met. It can be used multiple times.
  • If the path of execution steps into an if condition, it checks the predicate. If it returns true the control flow continues to the next line.
  • Predicate is a function or an expression that returns a boolean.
  • The difference between a loop and the if conditions is that loops can be executed more than once.
  • There are three types of loops;
    • While loop
    • For loop
    • Nested loop

While loop

  • The while loop is similar to the if statement but you use the while keyword instead of if.
  • The syntax for the while loop //initialize the counter while(condition){ //put the code here // increment or decrement counter }
  • The difference between the while loop and the if condition is that the while loop can call its body more than once. If condition will never call its body more than once.
fun main() {
    var number = 99
   while(number <= 120){
      if(number%2 == 0)
          println(number)
          number++;
      }
 }
Enter fullscreen mode Exit fullscreen mode

The code above prints the even numbers between 99 and 120

  • We can also use the while loop to print a sequence.
 fun main() {
    var number = 99
   while(number < 120){
          println("$number")
          number = number+3;
      }
 }
Enter fullscreen mode Exit fullscreen mode

The sequence created increases by 3 until the maximum number set is reached.

For loop

  • For loops are mostly used to iterate over group of elements.
 fun main() {
    var listOfnumber = listOf(99,102,105,108,111,114,117) 
   for(number in listOfnumber){
       println("On of the numbers in the list is $number")
   }
 } 
Enter fullscreen mode Exit fullscreen mode

The output of the code above is;

  1. On of the numbers in the list is 99
  2. On of the numbers in the list is 102
  3. On of the numbers in the list is 105
  4. On of the numbers in the list is 108
  5. On of the numbers in the list is 111
  6. On of the numbers in the list is 114
  7. On of the numbers in the list is 117
  • The for loop can be used to iterate over numbers in both a closed and open range.
  • In closed range, we use .. to print the numbers given. The last value given in a loop is printed. It shows the range.
fun main() {
    //closed range 
for(number in 91..100){
       println(number)
   }
}
Enter fullscreen mode Exit fullscreen mode

The output of code will print numbers between 91 to 100.

  • In open range, we use until to print the numbers given. The last value given in a loop is not printed.
fun main() {
    //open range 
for(number in 91 until 100){
       println(number)
   }
}
Enter fullscreen mode Exit fullscreen mode

The output of code will print numbers between 91 to 99.

  • The for loop can be used to increment and decrement an iteration through step keyword and downTo keyword.
fun main() {
    //closed range 
for(number in 91 until 100  step 3){
       println(number)
   }
}
Enter fullscreen mode Exit fullscreen mode

The output of the above code is 91,94,97. The step keyword increases a number by three after every iteration.

fun main() {
    for(number in 100 downTo 90){
       print(number)
   }
}
Enter fullscreen mode Exit fullscreen mode

The output of the above code will be printed from 100 backward to 90. We can also move backward with a certain number of steps using the step keyword as shown below.

fun main() {
    for(number in 100 downTo 90 step 3){
       println(number)
   }
}
Enter fullscreen mode Exit fullscreen mode

The output of the code will be 100,97,94,91

Nested Loop

  • This is a loop inside another loop.
  • The outer loop prints the number of rows while the inner loop prints the body.
fun main() {
    for(i in 1..5){
    for(j in 1..i){
        print("*")
    }
    println()
   }
}
Enter fullscreen mode Exit fullscreen mode

The output of the above code will print a triangle of stars.

*
**
***
****
*****
Enter fullscreen mode Exit fullscreen mode

Thank you for taking the time to read my article. I hope the ending left you with a lasting impression and that you will return for more thought-provoking content in Android and Kotlin in the future.

Imagekk
Be on the watch for modules two and three where we will deep dive into functions, classes and advanced classes in Kotlin. See you soon

syn

💖 💪 🙅 🚩
dbriane208
Daniel Brian

Posted on March 26, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related