Kotlin Basics Part One

 

Kotlin logo

Introduction

    In this article, I will talk about Kotlin basics: Basic types, Operators, Variables and Nullability. At the end of the article, there is a quiz to check your understanding of the concepts explained. We don't really have to memorise the syntax of any programming language. Most senior developers google printing a string in a specific language, We need to focus more on practicing the concepts as there are tons of cheat sheets out there, In addition, I will provide at the end of the articles' series. 

To practice Kotlin

A woman sitting on a couch and using her 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

Basic Types in Kotlin

    Kotlin treats everything as if they are objects, so primitive types such as numbers, booleans and characters are objects. This means that we can call methods on them. For example, we can call the following methods on numbers: toLong(), toByte(), toInt() and more. 

    Numbers have a supertype called Number. Supertype is "a generic entity type that has a relationship with one or more subtypes" as Oracle explains it. 

    Kotlin allows us to use object wrappers, which is a class that encases a primitive data type or another object to either convert it to a class or make it compatible with a newer version. It is called boxing. This will be explained later when needed.

Operators in Kotlin

    These are the mathematical operators:

 //Addition

2 + 2                                                          

res0: kotlin.Int = 4

 //Subtraction 

99 - 12                                                       

res1: kotlin.Int = 87

 //Division

20 / 5                                                          

res2: kotlin.Int = 4

3 / 6

//Integer divided by Integer returns Integer

res3: kotlin.Int = 0                                

3.0 / 6.0

// Float divided by float returns float

res4: kotlin.Double = 0.5   

 //Multiplication                 

6 * 30                                                           

res5: kotlin.Int = 180

A bubble that says that Koltin treats numbers as objects and we can call methods on them

 //Multiplication 

3.times(6)                                                 

res0: kotlin.Int = 18

//Division

18.div(2)                                                           

res1: kotlin.Int = 9

 //Addition

9.plus(2)                                                           

res2: kotlin.Int = 11

 //Subtraction 

15.minus(2)                                                      

res3: kotlin.Int = 13 reres: kotlin.Int = 9s1: kotlin.Int = 9

Variables in Kotlin

    There are two ways to define variables in Kotlin:
A bubble that says val: This keyword is for read  only variables that can only  be assigned once.

 //A variable of type string called firstName of value Leila

val firstName: String = "Leila"     

A bubble that says var: This keyword is for a  variable that can  reassigned.

 //A variable of type integer called age of value 20

var  age: Int = 20     

//The type, Int,  is inferred in the next line of code

//Once the type of the variable is determined, you cannot change it later. 

var age = 20         

//The type is needed in the next line of code, since it is not initialized

var age: Int

Basic Types in Kotlin Cont.

    Numbers will not convert their type once we assign them. As the next example shows, we will get an error for mismatched type.

val byteNumber: Byte = 2             

val intNumber: Int = byteNumber                                        

error: type mismatch: inferred type is Byte but Int was expected


    To solve this problem, you can cast the variable as follows:

val byteNumber: Byte = 2             

val intNumber: Int = byteNumber.toInt()                                        


Koltin recognizes variable types when we use underscores for long constants, which means the type is inferred. As follows:

val threeMillion = 3_000_000                                      


Nullability in Kotlin

    In Kotlin, Null pointer exception is avoided. Null pointer exception is when an application attempts to use a null value where an object is needed. You can check "Hello, Kotlin!" blog post to check my illustration to explain Null. By default, we can't assign a Null value to a variable, but we can use the question mark operator that will specify that this variable can be Null. Check the code below:

val pizza: Int = null      

error: null can not be a value of a non-null type Int

//The correct way

val pizza: Int? = null  

//Another correct way, here its type is inferred

val pizza = null              


    For complex data types, for example, a list, the list itself can be null and / or its elements. If the value of the list is not null, the elements themselves cannot be null. This means, If the list is nullable, its value has two options: null or a list of elements. These lists of elements if they are a nullable type, they can be null otherwise they cannot.  Lists will be explained later. But lets check its syntax:


//A list of two elements that are Null

var pizzaTypes: List<String?> = listOf(null, null)  

//Another correct way

listOf(null, null)

 res0: kotlin.collections.List<kotlin.Nothing?> = [null, null]

//A null list     

var pizzaTypes: List<String>? = null

//A null list & null elements

var pizzaTypes: List<String?>? = null

pizzaTypes = listOf(null, null)

// If the value of the list is not null, and the elements are not of a nullable type, then the elements themselves cannot be null.

var pizzaTypes: List<String>? = listOf(null, null)

error: type inference failed. Expected type mismatch: inferred type is List<String?> but List<String>? was expected

    There is a way to not avoid the null exception, we can throw an exception when the value is null. By using the double exclmation mark, also called "double bang", we can do so as follows:

var cookies: Int? = 4

cookies= null

cookies!!.plus(3)

kotlin.KotlinNullPointerException

Null Testing with Question Mark Operator

By using this method, it will reduce the use of if-else statements. ?: is called the elvis operator.

//The following line of code means, If drinks is not null, the output would be a value which in this case 7, as dec will decrement the value of drinks so 8-1= 7, but if it was null, the output would have been 0

var drinks = 8

drinks?.dec() ?: 0

res0: kotlin.Int = 7


Now it is time for a quiz.
A bubble that says A Happy  thought: No punctuation  at the end of the line  in Kotlin

QuizA book with right and wrong illustartion

1. What is the output for this line of code: 9 / 2 ?



2. Which Variable keyword you can use that can be reassigned?



3. Which one is the correct syntax?



4. What is the output of this code: 

        var chips: Int? = null 

        chips?.dec() ?: 0




    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