Category: Kotlin

  • Functions

    Kotlin is a statically typed language, hence, functions play a great role in it. We are pretty familiar with function, as we are using function throughout our examples in our last chapters. A function is a block of code which is written to perform a particular task. Functions are supported by all the modern programming languages and they are also known as methods or subroutines.

    At a broad level, a function takes some input which is called parameters, perform certain actions on these inputs and finally returns a value.

    Kotlin Built-in Functions

    Kotlin provides a number of built-in functions, we have used a number of buil-in functions in our examples. For example print() and println() are the most commonly used built-in function which we use to print an output to the screen.

    Example

    funmain(args: Array<String>){println("Hello, World!")}

    User-Defined Functions

    Kotlin allows us to create our own function using the keyword fun. A user defined function takes one or more parameters, perform an action and return the result of that action as a value.

    Syntax

    funfunctionName(){// body of function }

    Once we defined a function, we can call it any number of times whenever it is needed. Following isa simple syntax to call a Kotlin function:

    functionName()

    Example

    Following is an example to define and call a user-defined function which will print simple “Hello, World!”:

    funmain(args: Array<String>){printHello()}funprintHello(){println("Hello, World!")}

    When you run the above Kotlin program, it will generate the following output:

    Hello, World!
    

    Function Parameters

    A user-defined function can take zero or more parameters. Parameters are options and can be used based on requirement. For example, our above defined function did not make use of any paramenter.

    Example

    Following is an example to write a user-defined function which will add two given numbers and print their sum:

    funmain(args: Array<String>){val a =10val b =20printSum(a, b)}funprintSum(a:Int, b:Int){println(a + b)}

    When you run the above Kotlin program, it will generate the following output:

    30
    

    Return Values

    A kotlin function return a value based on requirement. Again it is very much optional to return a value.

    To return a value, use the return keyword, and specify the return type after the function’s parantheses

    Example

    Following is an example to write a user-defined function which will add two given numbers and return the sum:

    funmain(args: Array<String>){val a =10val b =20val result =sumTwo(a, b)println( result )}funsumTwo(a:Int, b:Int):Int{val x = a + b
       
       return x
    }

    When you run the above Kotlin program, it will generate the following output:

    30
    

    Unit-returning Functions

    If a function does not return a useful value, its return type is Unit. Unit is a type with only one value which is Unit.

    funsumTwo(a:Int, b:Int):Unit{val x = a + b
       
       println( x )}

    The Unit return type declaration is also optional. The above code is equivalent to:

    funsumTwo(a:Int, b:Int){val x = a + b
       
       println( x )}

    Kotlin Recursive Function

    Recursion functions are useful in many scenerios like calculating factorial of a number or generating fibonacci series. Kotlin supports recursion which means a Kotlin function can call itself.

    Syntax

    funfunctionName(){...functionName()...}

    Example

    Following is a Kotlin program to calculate the factorial of number 10:

    funmain(args: Array<String>){val a =4val result =factorial(a)println( result )}funfactorial(a:Int):Int{val result:Int
       
       if( a <=1){
    
      result = a
    }else{
      result = a*factorial(a-1)}return result
    }

    When you run the above Kotlin program, it will generate the following output:

    24
    

    Kotlin Tail Recursion

    A recursive function is eligible for tail recursion if the function call to itself is the last operation it performs.

    Example

    Following is a Kotlin program to calculate the factorial of number 10 using tail recursion. Here we need to ensure that the multiplication is done before the recursive call, not after.

    funmain(args: Array<String>){val a =4val result =factorial(a)println( result )}funfactorial(a: Int, accum: Int =1): Int {val result = a * accum
    
    returnif(a &lt;=1){
        result
    }else{factorial(a -1, result)}}</code></pre>

    When you run the above Kotlin program, it will generate the following output:

    24
    

    Kotlin tail recursion is useful while calculating factorial or some other processing on large numbers. So to avoide java.lang.StackOverflowError, you must use tail recursion.

    Higher-Order Functions

    A higher-order function is a function that takes another function as parameter and/or returns a function.

    Example

    Following is a function which takes two integer parameters, a and b and additionally, it takes another function operation as a parameter:

    funmain(args: Array<String>){val result =calculate(4,5,::sum)println( result )}funsum(a: Int, b: Int)= a + b 
    
    funcalculate(a: Int, b: Int, operation:(Int, Int)-> Int): Int {returnoperation(a, b)}

    When you run the above Kotlin program, it will generate the following output:

    9
    

    Here we are calling the higher-order function passing in two integer values and the function argument ::sum. Here :: is the notation that references a function by name in Kotlin.

    Example

    Let's look one more example where a function returns another function. Here we defined a higher-order function that returns a function. Here (Int) -> Int represents the parameters and return type of the square function.

    funmain(args: Array<String>){val func =operation()println(func(4))}funsquare(x: Int)= x * x
    
    funoperation():(Int)-> Int {return::square                                       
    }

    When you run the above Kotlin program, it will generate the following output:

    9
    

    Kotlin Lambda Function

    Kotlin lambda is a function which has no name and defined with a curly braces {} which takes zero or more parameters and body of function.

    The body of function is written after variable (if any) followed by -> operator.

    Syntax

    {variable with type -> body of the function}

    Example

    funmain(args: Array<String>){val upperCase ={ str: String -> str.toUpperCase()}println(upperCase("hello, world!"))}

    When you run the above Kotlin program, it will generate the following output:

    HELLO, WORLD!
    

    Kotlin Inline Function

    An inline function is declared with inline keyword. The use of inline function enhances the performance of higher order function. The inline function tells the compiler to copy parameters and functions to the call site.

    Example

    funmain(args: Array<String>){myFunction({println("Inline function parameter")})}inlinefunmyFunction(function:()-> Unit){println("I am inline function - A")function()println("I am inline function - B")}

    When you run the above Kotlin program, it will generate the following output:

    I am inline function - A
    Inline function parameter
    I am inline function - B
    
  • Ranges

    Kotlin range is defined by its two endpoint values which are both included in the range. Kotlin ranges are created with rangeTo() function, or simply using downTo or (. .) operators. The main operation on ranges is contains, which is usually used in the form of in and !in operators.

    Example

    1..10// Range of integers starting from 1 to 10
    
    a..z   // Range of characters starting from a to z
    
    A..Z   // Range of capital characters starting from A to Z

    Both the ends of the range are always included in the range which means that the 1..4 expression corresponds to the values 1,2,3 and 4.

    Creating Ranges using rangeTo()

    To create a Kotlin range we call rangeTo() function on the range start value and provide the end value as an argument.

    Example

    funmain(args: Array<String>){for( num in1.rangeTo(4)){println(num)}}

    When you run the above Kotlin program, it will generate the following output:

    1
    2
    3
    4
    

    Creating Ranges using .. Operator

    The rangeTo() is often called in its operator form ... So the above code can be re-written using .. operator as follows:

    Example

    funmain(args: Array<String>){for( num in1..4){println(num)}}

    When you run the above Kotlin program, it will generate the following output:

    1
    2
    3
    4
    

    Creating Ranges using downTo() Operator

    If we want to define a backward range we can use the downTo operator:

    Example

    funmain(args: Array<String>){for( num in4 downTo 1){println(num)}}

    When you run the above Kotlin program, it will generate the following output:

    4
    3
    2
    1
    

    Kotlin step() Function

    We can use step() function to define the distance between the values of the range. Let’s have a look at the following example:

    Example

    funmain(args: Array<String>){for( num in1..10 step 2){println(num)}}

    When you run the above Kotlin program, it will generate the following output:

    1
    3
    5
    7
    9
    

    Kotlin range of Characters

    Ranges can be created for characters like we have created them for integer values.

    Example

    funmain(args: Array<String>){for( ch in'a'..'d'){println(ch)}}

    When you run the above Kotlin program, it will generate the following output:

    a
    b
    c
    d
    

    Kotlin reversed() Function

    The function reversed() can be used to reverse the values of a range.

    Example

    funmain(args: Array<String>){for( num in(1..5).reversed()){println(num)}}

    When you run the above Kotlin program, it will generate the following output:

    5
    4
    3
    2
    1
    

    Kotlin until() Function

    The function until() can be used to create a range but it will skip the last element given.

    Example

    funmain(args: Array<String>){for( num in1 until 5){println(num)}}

    When you run the above Kotlin program, it will generate the following output:

    1
    2
    3
    4
    

    The last, first, step Elements

    We can use firstlast and step properties of a range to find the first, the last value or the step of a range.

    Example

    funmain(args: Array<String>){println((5..10).first)println((5..10 step 2).step)println((5..10).reversed().last)}

    When you run the above Kotlin program, it will generate the following output:

    5
    2
    5
    

    Filtering Ranges

    The filter() function will return a list of elements matching a given predicate:

    Example

    funmain(args: Array<String>){val a =1..10val f = a.filter{ T -> T %2==0}println(f)}

    When you run the above Kotlin program, it will generate the following output:

    [2, 4, 6, 8, 10]
    

    Distinct Values in a Range

    The distinct() function will return a list of distinct values from a range having repeated values:

    Example

    funmain(args: Array<String>){val a =listOf(1,1,2,4,4,6,10)println(a.distinct())}

    When you run the above Kotlin program, it will generate the following output:

    [1, 2, 4, 6, 10]
    

    Range Utility Functions

    There are many other useful functions we can apply to our range, like minmaxsumaveragecount:

    Example

    funmain(args: Array<String>){val a =1..10println(a.min())println(a.max())println(a.sum())println(a.average())println(a.count())}

    When you run the above Kotlin program, it will generate the following output:

    1
    10
    55
    5.5
    10
    
  • Arrays

    Arrays are used to store multiple items of the same data-type in a single variable, such as an integer or string under a single variable name.

    For example, if we need to store names of 1000 employees, then instead of creating 1000 different string variables, we can simply define an array of string whose capacity will be 1000.

    Like any other modern programming languages, Kotlin also supports arrays and provide a wide range of array properties and support functions to manipulate arrays.

    Creating Arrays in Kotlin

    To create an array in Kotlin, we use the arrayOf() function, and place the values in a comma-separated list inside it:

    val fruits =arrayOf("Apple","Mango","Banana","Orange")

    Optionally we can provide a data type as follows:

    val fruits = arrayOf<String>("Apple","Mango","Banana","Orange")

    Alternatively, the arrayOfNulls() function can be used to create an array of a given size filled with null elements.

    Primitive type Arrays

    Kotlin also has some built-in factory methods to create arrays of primitive data types. For example, the factory method to create an integer array is:

    val num =intArrayOf(1,2,3,4)

    Other factory methods available for creating arrays:

    • byteArrayOf()
    • charArrayOf()
    • shortArrayOf()
    • longArrayOf()

    Get and Set the Elements of an Array

    We can access an array element by using the index number inside square brackets. Kotlin array index starts with zero (0). So if you want to access 4th element of the array then you will need to give 3 as the index.

    Example

    funmain(args: Array<String>){val fruits = arrayOf<String>("Apple","Mango","Banana","Orange")println( fruits [0])println( fruits [3])}

    When you run the above Kotlin program, it will generate the following output:

    Apple
    Orange
    

    Kotlin also provides get() and set() member functions to get and set the value at a particular index. Check the following example:

    Example

    funmain(args: Array<String>){val fruits = arrayOf<String>("Apple","Mango","Banana","Orange")println( fruits.get(0))println( fruits.get(3))// Set the value at 3rd index
       fruits.set(3,"Guava")println( fruits.get(3))}

    When you run the above Kotlin program, it will generate the following output:

    Apple
    Orange
    Guava
    

    Kotlin Array Length

    Kotlin provides array property called size which returns the size i.e. length of the array.

    Example

    funmain(args: Array<String>){val fruits = arrayOf<String>("Apple","Mango","Banana","Orange")println("Size of fruits array "+ fruits.size )}

    When you run the above Kotlin program, it will generate the following output:

    Size of fruits array 4
    

    We can also use count() member function to get the size of the array.

    Loop Through an Array

    We can use for loop to loop through an array.

    Example

    funmain(args: Array<String>){val fruits = arrayOf<String>("Apple","Mango","Banana","Orange")for( item in fruits ){println( item )}}

    When you run the above Kotlin program, it will generate the following output:

    Apple
    Mango
    Banana
    Orange
    

    Check if an Element Exists

    We can use the in operator alongwith if…else to check if an element exists in an array.

    Example

    funmain(args: Array<String>){val fruits = arrayOf<String>("Apple","Mango","Banana","Orange")if("Mango"in fruits){println("Mango exists in fruits")}else{println("Mango does not exist in fruits")}}

    When you run the above Kotlin program, it will generate the following output:

    Mango exists in fruits
    

    Distinct Values from Array

    Kotlin allows to store duplicate values in an array, but same time you can get a set of distinct values stored in the array using distinct() member function.

    Example

    funmain(args: Array<String>){val fruits = arrayOf<String>("Apple","Mango","Banana","Orange","Apple")val distinct = fruits.distinct()for( item in distinct ){println( item )}}

    When you run the above Kotlin program, it will generate the following output:

    Apple
    Mango
    Banana
    Orange
    

    Dropping Elements from Array

    We can use drop() or dropLast() member functions to drop elements from the beginning or from the last respectively.

    Example

    funmain(args: Array<String>){val fruits = arrayOf<String>("Apple","Mango","Banana","Orange","Apple")val result = fruits.drop(2)// drops first two elements.for( item in result ){println( item )}}

    When you run the above Kotlin program, it will generate the following output:

    Banana
    Orange
    Apple
    

    Checking an Empty Array

    We can use isEmpty() member function to check if an array is empty or not. This function returns true if the array is empty.

    Example

    funmain(args: Array<String>){val fruits = arrayOf<String>()println("Array is empty : "+ fruits.isEmpty())}

    When you run the above Kotlin program, it will generate the following output:

    "Array is empty : true
    
  • Strings

    The Kotlin String data type is used to store a sequence of characters. String values must be surrounded by double quotes (” “) or triple quote (“”” “””).

    We have two kinds of string available in Kotlin – one is called Escaped String and another is called Raw String.

    • Escaped string is declared within double quote (” “) and may contain escape characters like ‘\n’, ‘\t’, ‘\b’ etc.
    • Raw string is declared within triple quote (“”” “””) and may contain multiple lines of text without any escape characters.

    Example

    funmain(args: Array<String>){val escapedString : String  ="I am escaped String!\n"var rawString :String  ="""This is going to be a
       multi-line string and will
       not have any escape sequence""";print(escapedString)println(rawString)}

    When you run the above Kotlin program, it will generate the following output:

    I am escaped String!
    This is going to be a
       multi-line string and will
       not have any escape sequence
    

    This is optional to specify the data type for a String, Kotlin can understand that the a variable is a String because of the given double or tripple quotes.

    If you want to create a String variable without assigning the value then you must specify the type while declaring the variable otherwise it will raise an error:

    funmain(args: Array<String>){val name : String
    
       name ="Zara Ali"println(name)}

    When you run the above Kotlin program, it will generate the following output:

    Zara Ali
    

    Kotlin String Templates

    Kotlin string templates are pieces of code that are evaluated and whose results are interpolated into the string. A template expression starts with a dollar sign ($) and may consist of either a name or an expression.

    funmain(args: Array<String>){val name : String ="Zara Ali"println("Name  - $name")// Using template with variable nameprintln("Name length - ${name.length}")// Using template with expression.}

    When you run the above Kotlin program, it will generate the following output:

    Name - Zara Ali
    Name length - 8
    

    Kotlin String Object

    Kotlin String is an object, which contains a number of properties and functions that can perform certain operations on strings, by writing a dot character (.) after the specific string variable.

    We will see some of the important properties and functions in this chapter, remaining you can find in official documentation of Kotlin latest version.

    Kotlin String Indexes

    Kotlin String can be treated as a sequence of characters or you can say String is an array of characters. You can access its element by specifying the index of the element using a square brackets.

    String indexes start with 0, so if you want to access 4th element of the string then you should specify index as 3 to access the 4th element.

    Example

    funmain(args: Array<String>){val name : String ="Zara Ali"println(name[3])println(name[5])}

    When you run the above Kotlin program, it will generate the following output:

    a
    A
    

    Kotlin String Length

    We can use length property of Kotlin string to find out its length.

    Kotlin function count() also returns the length of a given string.

    Example

    funmain(args: Array<String>){val name : String ="Zara Ali"println("The length of name :"+ name.length)println("The length of name :"+ name.count())}

    When you run the above Kotlin program, it will generate the following output:

    The length of name :8
    The length of name :8
    

    Kotlin String Last Index

    We can use lastIndex property of Kotlin string to find out the index of the last character in the char sequence. If a string is empty then it returns a -1.

    Example

    funmain(args: Array<String>){val name : String ="Zara Ali"println("The index of last character in name :"+ name.lastIndex)}

    When you run the above Kotlin program, it will generate the following output:

    The index of last character in name :7
    

    Changing Case of Strings

    Kotlin provides toUpperCase() and toLowerCase() functions to convert a string into upper case and lower case respectively.

    Example

    funmain(args: Array<String>){val name : String ="Zara Ali"println("Upper case of name :"+ name.toUpperCase())println("Lower case of name :"+ name.toLowerCase())}

    When you run the above Kotlin program, it will generate the following output:

    Upper case of name :ZARA ALI
    Lower case of name :zara ali
    

    Kotlin String Concatenation

    We can use either + operator to concatenate two strings, or we can also use plus() function to concatenate two strings.

    Example

    funmain(args: Array<String>){var firstName : String ="Zara "var lastName : String ="Ali"println("Full Name :"+ firstName + lastName)println("Full Name :"+ firstName.plus(lastName))}

    When you run the above Kotlin program, it will generate the following output:

    Full Name :Zara Ali
    Full Name :Zara Ali
    

    Trim Characters from a String

    We can remove first few or last few characters from a string using drop() or dropLast() functions.

    Example

    funmain(args: Array<String>){var name : String ="Zara Ali"println("Remove first two characters from name : "+ name.drop(2))println("Remove last two characters from name : "+ name.dropLast(2))}

    When you run the above Kotlin program, it will generate the following output:

    Remove first two characters from name : ra Ali
    Remove last two characters from name : Zara A
    

    Quotes Inside a String

    To use quotes inside a string, use single quotes (‘):

    Example

    funmain(args: Array<String>){var str1 : String ="That's it"var str2 : String ="It's OK"println("str1 : "+ str1)println("str2 : "+ str2)}

    When you run the above Kotlin program, it will generate the following output:

    str1 : That's it
    str2 : It's OK
    

    Finding a String inside a String

    Kotlin provides indexOf() function to find out a text inside a string. This function returns the index of the first occurrence of a specified text in a string

    Example

    funmain(args: Array<String>){var str : String ="Meditation and Yoga are synonymous with India"println("Index of Yoga in the string - "+ str.indexOf("Yoga"))}

    When you run the above Kotlin program, it will generate the following output:

    Index of Yoga in the string - 15
    

    Comparing Two Strings

    Kotlin provides compareTo() function to compare two strings. This function returns 0 if two strings are equal otherwise it will return 1.

    Example

    funmain(args: Array<String>){var str1 : String ="Apple"var str2 : String ="Apple"println(str1.compareTo(str2))}

    When you run the above Kotlin program, it will generate the following output:

    0
    

    Kotlin getOrNull() function

    Kotlin getOrNull() function returns a character at the given index or null if the index is out of bounds of this char sequence.

    Example

    funmain(args: Array<String>){var name : String ="Zara"println(name.getOrNull(0))println(name.getOrNull(2))println(name.getOrNull(100))}

    When you run the above Kotlin program, it will generate the following output:

    Z
    r
    null
    

    Kotlin toString() function

    Kotlin toString() function returns a string representation of the object..

    Example

    funmain(args: Array<String>){var name : String ="Zara Ali"println(name.toString())}

    When you run the above Kotlin program, it will generate the following output:

    Zara Ali
    
  • Booleans

    Many times we come across a situation where we need to take decision in Yes or No, or may be we can say True or False. To handle such situation Kotlin has a Boolean data type, which can take the values either true or false.

    Kotlin also has a nullable counterpart Boolean? that can have the null value.

    Create Boolean Variables

    A boolean variable can be created using Boolean keyword and this variable can only take the values either true or false:

    Example

    funmain(args: Array<String>){val isSummer: Boolean =trueval isCold: Boolean =falseprintln(isSummer)println(isCold)}

    When you run the above Kotlin program, it will generate the following output:

    true
    false
    

    In fact, we can create Kotlin boolean variables without using Boolean keyword and Kotlin will understand the variable type based on the assigned values either true or false

    Kotlin Boolean Operators

    Kotlin provides following built-in operators for boolean variables. These operators are also called Logical Operators:

    OperatorNameDescriptionExample
    &&Logical andReturns true if both operands are truex && y
    ||Logical orReturns true if either of the operands is truex || y
    !Logical notReverse the result, returns false if the operand is true!x

    Example

    Following example shows different calculations using Kotlin Logical Operators:

    funmain(args: Array<String>){var x: Boolean =truevar y:Boolean =falseprintln("x && y = "+(x && y))println("x || y = "+(x || y))println("!y = "+(!y))}

    When you run the above Kotlin program, it will generate the following output:

    x && y = false
    x || y = true
    !y = true
    

    Kotlin Boolean Expression

    A Boolean expression returns either true or false value and majorly used in checking the condition with if…else expressions. A boolean expression makes use of relational operators, for example >, <, >= etc.

    funmain(args: Array<String>){val x: Int =40val y: Int =20println("x > y = "+(x > y))println("x < y = "+(x < y))println("x >= y = "+(x >= y))println("x <= y = "+(x <= y))println("x == y = "+(x == y))println("x != y = "+(x != y))}

    When you run the above Kotlin program, it will generate the following output:

    x > y = true
    x < y = false
    x >= y = true
    x <= y = false
    x == y = false
    x != y = true
    

    Kotlin and()and or() Functions

    Kotlin provides and() and or() functions to perform logical AND and logical OR operations between two boolean operands.

    These functions are different from && and || operators because these functions do not perform short-circuit evaluation but they always evaluate both the operands.

    funmain(args: Array<String>){val x: Boolean =trueval y: Boolean =falseval z: Boolean =trueprintln("x.and(y) = "+  x.and(y))println("x.or(y) = "+  x.or(y))println("x.and(z) = "+  x.and(z))}

    When you run the above Kotlin program, it will generate the following output:

    x.and(y) = false
    x.or(y) = true
    x.and(z) = true
    

    Kotlin also provides not() and xor() functions to perform Logical NOT and XOR operations respectively.

    Boolean to String

    You can use toString() function to convert a Boolean object into its equivalent string representation.

    You will need this conversion when assigning a true or false value in a String variable.

    funmain(args: Array<String>){val x: Boolean =truevar z: String
       
       z = x.toString()println("x.toString() = "+  x.toString())println("z = "+  z)}

    When you run the above Kotlin program, it will generate the following output:

    x.toString() = true
    z = true
    
  • Operators

    An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Kotlin is rich in built-in operators and provide the following types of operators:

    • Arithmetic Operators
    • Relational Operators
    • Assignment Operators
    • Unary Operators
    • Logical Operators
    • Bitwise Operations

    Now let’s look into these Kotlin Operators one by one.

    (a) Kotlin Arithmetic Operators

    Kotlin arithmetic operators are used to perform basic mathematical operations such as addition, subtraction, multiplication and division etc.

    OperatorNameDescriptionExample
    +AdditionAdds together two valuesx + y
    SubtractionSubtracts one value from anotherx – y
    *MultiplicationMultiplies two valuesx * y
    /DivisionDivides one value by anotherx / y
    %ModulusReturns the division remainderx % y

    Example

    Following example shows different calculations using Kotlin Arithmetic Operators:

    funmain(args: Array<String>){val x: Int =40val y: Int =20println("x + y = "+(x + y))println("x - y = "+(x - y))println("x / y = "+(x / y))println("x * y = "+(x * y))println("x % y = "+(x % y))}

    When you run the above Kotlin program, it will generate the following output:

    x + y = 60
    x - y = 20
    x / y = 2
    x * y = 800
    x % y = 0
    

    (b) Kotlin Relational Operators

    Kotlin relational (comparison) operators are used to compare two values, and returns a Boolean value: either true or false.

    OperatorNameExample
    >greater thanx > y
    <less thanx < y
    >=greater than or equal tox >= y
    <=less than or equal tox <= y
    ==is equal tox == y
    !=not equal tox != y

    Example

    Following example shows different calculations using Kotlin Relational Operators:

    funmain(args: Array<String>){val x: Int =40val y: Int =20println("x > y = "+(x > y))println("x < y = "+(x < y))println("x >= y = "+(x >= y))println("x <= y = "+(x <= y))println("x == y = "+(x == y))println("x != y = "+(x != y))}

    When you run the above Kotlin program, it will generate the following output:

    x > y = true
    x < y = false
    x >= y = true
    x <= y = false
    x == y = false
    x != y = true
    

    (c) Kotlin Assignment Operators

    Kotlin assignment operators are used to assign values to variables.

    Following is an example where we used assignment operator = to assign a values into two variables:

    funmain(args: Array<String>){val x: Int =40val y: Int =20println("x = "+  x)println("y = "+  y)}

    When you run the above Kotlin program, it will generate the following output:

    x = 40
    y = 20
    

    Following is one more example where we used assignment operator += to add the value of self variable and assign it back into the same variable:

    funmain(args: Array<String>){var x: Int =40
    
       x +=10println("x = "+  x)}

    When you run the above Kotlin program, it will generate the following output:

    x = 50
    

    Following is a list of all assignment operators:

    OperatorExampleExpanded Form
    =x = 10x = 10
    +=x += 10x = x – 10
    -=x -= 10x = x – 10
    *=x *= 10x = x * 10
    /=x /= 10x = x / 10
    %=x %= 10x = x % 10

    Example

    Following example shows different calculations using Kotlin Assignment Operators:

    funmain(args: Array<String>){var x: Int =40
    
       x +=5println("x += 5 = "+ x )
       
       x =40;
       x -=5println("x -= 5 = "+  x)
       
       x =40
       x *=5println("x *= 5 = "+  x)
       
       x =40
       x /=5println("x /= 5 = "+  x)
       
       x =43
       x %=5println("x %= 5 = "+ x)}

    When you run the above Kotlin program, it will generate the following output:

    x += 5 = 45
    x -= 5 = 35
    x *= 5 = 200
    x /= 5 = 8
    x %= 5 = 3
    

    (d) Kotlin Unary Operators

    The unary operators require only one operand; they perform various operations such as incrementing/decrementing a value by one, negating an expression, or inverting the value of a boolean.

    Following is the list of Kotlin Unary Operators:

    OperatorNameExample
    +unary plus+x
    unary minus-x
    ++increment by 1++x
    decrement by 1–x
    !inverts the value of a boolean!x

    Example

    Following example shows different calculations using Kotlin Unary Operators:

    funmain(args: Array<String>){var x: Int =40var b:Boolean =trueprintln("+x = "+(+x))println("-x = "+(-x))println("++x = "+(++x))println("--x = "+(--x))println("!b = "+(!b))}

    When you run the above Kotlin program, it will generate the following output:

    +x = 40
    -x = -40
    ++x = 41
    --x = 40
    !b = false
    

    Here increment (++) and decrement (–) operators can be used as prefix as ++x or –x as well as suffix as x++ or x–. The only difference between the two forms is that in case we use them as prefix then operator will apply before expression is executed, but if use them as suffix then operator will apply after the expression is executed.

    (e) Kotlin Logical Operators

    Kotlin logical operators are used to determine the logic between two variables or values:

    Following is the list of Kotlin Logical Operators:

    OperatorNameDescriptionExample
    &&Logical andReturns true if both operands are truex && y
    ||Logical orReturns true if either of the operands is truex || y
    !Logical notReverse the result, returns false if the operand is true!x

    Example

    Following example shows different calculations using Kotlin Logical Operators:

    funmain(args: Array<String>){var x: Boolean =truevar y:Boolean =falseprintln("x && y = "+(x && y))println("x || y = "+(x || y))println("!y = "+(!y))}

    When you run the above Kotlin program, it will generate the following output:

    x && y = false
    x || y = true
    !y = true
    

    (e) Kotlin Bitwise Operations

    Kotlin does not have any bitwise operators but Kotlin provides a list of helper functions to perform bitwise operations.

    Following is the list of Kotlin Bitwise Functions:

    FunctionDescriptionExample
    shl (bits)signed shift leftx.shl(y)
    shr (bits)signed shift rightx.shr(y)
    ushr (bits)unsigned shift rightx.ushr(y)
    and (bits)bitwise andx.and(y)
    or (bits)bitwise orx.or(y)
    xor (bits)bitwise xorx.xor(y)
    inv()bitwise inversex.inv()

    Example

    Following example shows different calculations using Kotlin bitwise functions:

    funmain(args: Array<String>){var x:Int =60// 60 = 0011 1100  var y:Int =13// 13 = 0000 1101var z:Int
    
       z = x.shl(2)// 240 = 1111 0000println("x.shl(2) = "+  z)
       
       z = x.shr(2)// 15 = 0000 1111println("x.shr(2) = "+  z)
       
       z = x.and(y)// 12 = 0000 1100println("x.and(y)  = "+  z)
       
       z = x.or(y)// 61 = 0011 1101println("x.or(y)  = "+  z)
       
       z = x.xor(y)// 49 = 0011 0001println("x.xor(y)  = "+  z)
       
       z = x.inv()// -61 = 1100 0011println("x.inv()  = "+  z)}

    When you run the above Kotlin program, it will generate the following output:

    x.shl(2) = 240
    x.shr(2) = 15
    x.and(y)  = 12
    x.or(y)  = 61
    x.xor(y)  = 49
    x.inv()  = -61
    
  • Data Types

    Kotlin data type is a classification of data which tells the compiler how the programmer intends to use the data. For example, Kotlin data could be numeric, string, boolean etc.

    Kotlin treats everything as an object which means that we can call member functions and properties on any variable.

    Kotlin is a statically typed language, which means that the data type of every expression should be known at compile time.

    Kotlin built in data type can be categorized as follows:

    • Number
    • Character
    • String
    • Boolean
    • Array

    (a) Kotlin Number Data Types

    Kotlin number data types are used to define variables which hold numeric values and they are divided into two groups: (a) Integer types store whole numbers, positive or negative (b) Floating point types represent numbers with a fractional part, containing one or more decimals.

    Following table list down all the Kotlin number data types, keywords to define their variable types, size of the memory taken by the variables, and a value range which can be stored in those variables.

    Data TypeSize (bits)Data Range
    Byte8 bit-128 to 127
    Short16 bit-32768 to 32767
    Int32 bit-2,147,483,648 to 2,147,483,647
    Long64 bit-9,223,372,036,854,775,808 to +9,223,372,036,854,775,807
    Float32 bit1.40129846432481707e-45 to 3.40282346638528860e+38
    Double64 bit4.94065645841246544e-324 to 1.79769313486231570e+308

    If we will try to store a value more than permitted value in a variable of particular data type, the Kotlin compiler will complain because an overflow would occur at runtime.

    Example

    Following example shows how to define and access different Kotlin number data types:

    funmain(args: Array<String>){val a: Int =10000val d: Double =100.00val f: Float =100.00fval l: Long =1000000004val s: Short =10val b: Byte =1println("Int Value is "+ a)println("Double  Value is "+ d)println("Float Value is "+ f)println("Long Value is "+ l )println("Short Value is "+ s)println("Byte Value is "+ b)}

    When you run the above Kotlin program, it will generate the following output:

    Int Value is 10000
    Double  Value is 100.0
    Float Value is 100.0
    Long Value is 1000000004
    Short Value is 10
    Byte Value is 1
    

    (b) Kotlin Character Data Type

    Kotlin character data type is used to store a single character and they are represented by the type Char keyword. A Char value must be surrounded by single quotes, like ‘A’ or ‘1’.

    Example

    Following example shows how to define and access a Kotlin Char data type:

    funmain(args: Array<String>){val letter: Char    // defining a Char variable
       letter ='A'// Assigning a value to itprintln("$letter")}

    When you run the above Kotlin program, it will generate the following output:

    A
    

    Kotlin supports a number of escape sequences of characters. When a character is preceded by a backslash (\), it is called an escape sequence and it has a special meaning to the compiler. For example, \n in the following statement is a valid character and it is called a new line character

    println('\n')//prints a newline characterprintln('\$')//prints a dollar $ characterprintln('\\')//prints a back slash \ character

    The following escape sequences are supported in Kotlin: \t, \b, \n, \r, \’, \”, \\ and \$.

    (c) Kotlin String Data Type

    The String data type is used to store a sequence of characters. String values must be surrounded by double quotes (” “) or triple quote (“”” “””).

    We have two kinds of string available in Kotlin – one is called Escaped String and another is called Raw String.

    • Escaped string is declared within double quote (” “) and may contain escape characters like ‘\n’, ‘\t’, ‘\b’ etc.
    • Raw string is declared within triple quote (“”” “””) and may contain multiple lines of text without any escape characters.
    funmain(args: Array<String>){val escapedString : String  ="I am escaped String!\n"var rawString :String  ="""This is going to be a
       multi-line string and will
       not have any escape sequence""";print(escapedString)println(rawString)}

    When you run the above Kotlin program, it will generate the following output:

    I am escaped String!
    This is going to be a
       multi-line string and will
       not have any escape sequence
    

    (d) Kotlin Boolean Data Type

    Boolean is very simple like other programming languages. We have only two values for Boolean data type – either true or false.

    funmain(args: Array<String>){val A: Boolean =true// defining a variable with true valueval B: Boolean =false// defining a variable with false valueprintln("Value of variable A "+ A )println("Value of variable B "+ B )}

    When you run the above Kotlin program, it will generate the following output:

    Value of variable A true
    Value of variable B false
    

    Boolean has a nullable counterpart Boolean? that can store a null value as below:

    val boolNull: Boolean?=null

    (e) Kotlin Array Data Type

    Kotlin arrays are a collection of homogeneous data. Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.

    We will study array in a separate chapter, for now let’s look at one example to define an array of integers and then access its one of the elements.

    funmain(args: Array<String>){val numbers: IntArray =intArrayOf(1,2,3,4,5)println("Value at 3rd position : "+ numbers[2])}

    When you run the above Kotlin program, it will generate the following output:

    Value at 3rd position : 3
    

    Kotlin Data Type Conversion

    Type conversion is a process in which the value of one data type is converted into another type. Kotlin does not support direct conversion of one numeric data type to another, For example, it is not possible to convert an Int type to a Long type:

    funmain(args: Array<String>){val x: Int =100val y: Long = x  // Not valid assignmentprintln(y)}

    When you run the above Kotlin program, it will generate the following output:

    main.kt:3:18: error: type mismatch: inferred type is Int but Long was expected
       val y: Long = x  // Not valid assignment
    

    To convert a numeric data type to another type, Kotlin provides a set of functions:

    • toByte()
    • toShort()
    • toInt()
    • toLong()
    • toFloat()
    • toDouble()
    • toChar()

    Now let’s rewrite above example once again and try to run it:

    funmain(args: Array<String>){val x: Int =100val y: Long = x.toLong()println(y)}

    When you run the above Kotlin program, it will generate the following output:

    100
    
  • Variables

    Variables are an important part of any programming. They are the names you give to computer memory locations which are used to store values in a computer program and later you use those names to retrieve the stored values and use them in your program.

    Kotlin variables are created using either var or val keywords and then an equal sign = is used to assign a value to those created variables.

    Syntax

    Following is a simple syntax to create two variables and then assign them different values:

    var name ="Zara Ali"var age =19var height =5.2

    Examples

    Once a variable is created and assigned a value, later we can access its value using its name as follows:

    funmain(){var name ="Zara Ali"var age =19println(name)println(age)}

    When you run the above Kotlin program, it will generate the following output:

    Zara Ali
    19
    

    Let’s see one more example where we will access variable values using dollar sign $:

    funmain(){var name ="Zara Ali"var age =19println("Name = $name")println("Age = $age")}

    When you run the above Kotlin program, it will generate the following output:

    Name = Zara Ali
    Age = 19
    

    Let’s see one more example to display the variable values without using a dollar sign as below:

    funmain(){var name ="Zara Ali"var age =19println("Name = "+ name)println("Age = "+ age)}

    When you run the above Kotlin program, it will generate the following output:

    Name = Zara Ali
    Age = 19
    

    Kotlin Mutable Variables

    Mutable means that the variable can be reassigned to a different value after initial assignment. To declare a mutable variable, we use the var keyword as we have used in the above examples:

    funmain(){var name ="Zara Ali"var age =19println("Name = $name")println("Age = $age")
       
       name ="Nuha Ali"
       age =11println("Name = $name")println("Age = $age")}

    When you run the above Kotlin program, it will generate the following output:

    Name = Zara Ali
    Age = 19
    Name = Nuha Ali
    Age = 11
    

    Kotlin Read-only Variables

    A read-only variable can be declared using val (instead of var) and once a value is assigned, it can not be re-assigned.

    funmain(){val name ="Zara Ali"val age =19println("Name = $name")println("Age = $age")
       
       name ="Nuha Ali"// Not allowed, throws an exception
       age =11println("Name = $name")println("Age = $age")}

    When you run the above Kotlin program, it will generate the following output:

    main.kt:8:4: error: val cannot be reassigned
       name = "Nuha Ali" // Not allowed, throws an exception
       ^
    main.kt:9:4: error: val cannot be reassigned
       age = 11
       ^
    

    Read-only vs Mutable

    The Mutable variables will be used to define variables, which will keep charging their values based on different conditions during program execution.

    You will use Read-only variable to define different constant values i.e. the variables which will retain their value throughout of the program.

    Kotlin Variable Types

    Kotlin is smart enough to recognise that “Zara Ali” is a string, and that 19 is a number variable. However, you can explicitly specify a variable type while creating it:

    funmain(){var name: String ="Zara Ali"var age: Int =19println("Name = $name")println("Age = $age")
       
       name ="Nuha Ali"
       age =11println("Name = $name")println("Age = $age")}

    When you run the above Kotlin program, it will generate the following output:

    Name = Zara Ali
    Age = 19
    Name = Nuha Ali
    Age = 11
    

    Soon we will learn more about different data types available in Kotlin which can be used to create different type of variables.

    Kotlin Variable Naming Rules

    There are certain rules to be followed while naming the Kotlin variables:

    • Kotlin variable names can contain letters, digits, underscores, and dollar signs.
    • Kotlin variable names should start with a letter or underscores
    • Kotlin variables are case sensitive which means Zara and ZARA are two different variables.
    • Kotlin variable can not have any white space or other control characters.
    • Kotlin variable can not have names like var, val, String, Int because they are reserved keywords in Kotlin.
  • Keywords

    Kotlin keywords are predefined, reserved words used in Kotlin programming that have special meanings to the compiler. These words cannot be used as an identifier (variables names, package names, function names etc.) and if used then compiler will raise an exception.

    Kotlin uses fun keyword to define a function, so if we we will try to use it as a variable name then it will be an exception. For example:

    funmain(){varfun="Zara Ali"// Not allowed, throws an exceptionvar age =19// Valid variable nameprintln("Name = $fun")println("Age = $age")}

    When you run the above Kotlin program, it will generate the following output:

    main.kt:2:7: error: expecting property name or receiver type
       var fun = "Zara Ali"  // Not allowed, throws an exception
    
      ^
    main.kt:2:11: error: expecting '(' var fun = "Zara Ali" // Not allowed, throws an exception
          ^
    main.kt:5:21: error: keyword cannot be used as a reference println("Name = $fun")
                    ^

    Kotlin keywords have been categorised into three broad categories: (a) Hard Keywords (b) Soft Keywords (c) Modifier Keywords

    As a good programming practice, it is highly recommended not to use any of the mentioned keywords to name any identifiers while coding in Kotlin.

    (a) Kotlin Hard Keywords

    Following is a list of hard keywords and they cannot be used as identifiers:

    asas?breakclass
    continuedoelsefalse
    forfunifin
    !ininterfaceis!is
    nullobjectpackagereturn
    superthisthrowtrue
    trytypealiastypeofval
    varwhenwhile

    (b) Kotlin Soft Keywords

    Following is the list of keywords (soft) in the context when they are applicable and can be used as identifiers in other contexts:

    bycatchconstructordelegate
    dynamicfieldfilefinally
    getimportinitparam
    propertyreceiversetsetparam
    valuewhere

    (c) Kotlin Modifier Keywords

    Following is the list of tokens which act as keywords in modifier lists of declarations and can be used as identifiers in other contexts:

    actualabstractannotationcompanion
    constcrossinlinedataenum
    expectexternalfinalinfix
    inlineinnerinternallateinit
    noinlineopenoperatorout
    overrideprivateprotectedpublic
    reifiedsealedsuspendtailrec
    vararg
  • Comments

    A comment is a programmer-readable explanation or annotation in the Kotlin source code. They are added with the purpose of making the source code easier for humans to understand, and are ignored by Kotlin compiler.

    Just like most modern languages, Kotlin supports single-line (or end-of-line) and multi-line (block) comments. Kotlin comments are very much similar to the comments available in Java, C and C++ programming languages.

    Kotlin Single-line Comments

    Single line comments in Kotlin starts with two forward slashes // and end with end of the line. So any text written in between // and the end of the line is ignored by Kotlin compiler.

    Following is the sample Kotlin program which makes use of a single-line comment:

    // This is a commentfunmain(){println("Hello, World!")}

    When you run the above Kotlin program, it will generate the following output:

    Hello, World!
    

    A single line comment can start from anywhere in the program and will end till the end of the line. For example, you can use single line comment as follows:

    funmain(){println("Hello, World!")// This is also a comment}

    Kotlin Multi-line Comments

    A multi-line comment in Kotlin starts with /* and end with */. So any text written in between /* and */ will be treated as a comment and will be ignored by Kotlin compiler.

    Multi-line comments also called Block comments in Kotlin.

    Following is the sample Kotlin program which makes use of a multi-line comment:

    /* This is a multi-line comment and it can span
     * as many lines as you like 
     */funmain(){println("Hello, World!")}

    When you run the above Kotlin program, it will generate the following output:

    Hello, Word!
    

    Kotlin Nested Comments

    Block comments in Kotlin can be nested, which means a single-line comment or multi-line comments can sit inside a multi-line comment as below:

    /* This is a multi-line comment and it can span
     * as many lines as you like 
     /* This is a nested comment */// Another nested comment */funmain(){println("Hello, World!")}

    When you run the above Kotlin program, it will generate the following output:

    Hello, World!