Category: Kotlin Tutorial

https://w7.pngwing.com/pngs/699/399/png-transparent-kotlin-programming-language-java-jvm-android-development-kotlin-logo-3d-icon-thumbnail.png

  • Kotlin Comment

    Comments are the statements that are used for documentation purpose. Comments are ignored by compiler so that don’t execute. We can also used it for providing information about the line of code. There are two types of comments in Kotlin.

    1. Single line comment.
    2. Multi line comment.

    Single line comment

    Single line comment is used for commenting single line of statement. It is done by using ‘//’ (double slash). For example:

    fun main(args: Array<String>) {  
    
    // this statement used for print   
    
        println("Hello World!")  
    
    } 

      Output

      Hello World!
      

      Multi line comment

      Multi line comment is used for commenting multiple line of statement. It is done by using /* */ (start with slash strict and end with star slash). For example:

      fun main(args: Array<String>) {  
      
      /* this statement 
      
         is used 
      
         for print */  
      
          println("Hello World!")  
      
      } 

        Output:

        Hello World!
        
      1. Kotlin Standard Input/Output

        Kotlin standard input output operations are performed to flow byte stream from input device (keyboard) to main memory and from main memory to output device (screen).

        Kotlin Output

        Kotlin output operation is performed using the standard methods print() and println(). Let’s see an example:

        fun main(args: Array<String>) {  
        
            println("Hello World!")  
        
            print("Welcome to  JavaTpoint")  
        
        }  

          Output

          Hello World!
          Welcome to  JavaTpoint
          

          The methods print() and println() are internally call System.out.print() and System.out.println() respectively.

          Difference between print() and println() methods:

          • print(): print() method is used to print values provided inside the method “()”.
          • println(): println() method is used to print values provided inside the method “()” and moves cursor to the beginning of next line.

          Example

          fun main(args: Array<String>){  
          
              println(10)  
          
              println("Welcome to  JavaTpoint")  
          
              print(20)  
          
              print("Hello")  
          
          }  

            Output:

            10
            Welcome to  JavaTpoint
            20Hello
            

            Kotlin Input

            Kotlin has standard library function readLine() which is used for reads line of string input from standard input stream. It returns the line read or null. Let’s see an example:

            fun main(args: Array<String>) {  
            
                println("Enter your name")  
            
                val name = readLine()  
            
                println("Enter your age")  
            
                var age: Int =Integer.valueOf(readLine())  
            
                println("Your name is $name and your age is $age")  
            
            } 

              Output:

              Enter your name
              Ashutosh
              Enter your age
              25
              Your name is Ashutosh and your age is 25
              

              While using the readLine() function, input lines other than String are explicitly converted into their corresponding types.

              To input other data type rather than String, we need to use Scanner object of java.util.Scanner class from Java standard library.

              Example Getting Integer Input

              import java.util.Scanner  
              
              fun main(args: Array<String>) {  
              
                  val read = Scanner(System.in)  
              
                  println("Enter your age")  
              
                  var age = read.nextInt()  
              
                  println("Your input age is "+age)  
              
              }  

                Output:

                Enter your age
                25
                Your input age is 25
                

                Here nextInt() is a method which takes integer input and stores in integer variable. The other data types Boolean, Float, Long and Double uses nextBoolean(), nextFloat(), nextLong() and nextDouble() to get input from user.

              1. Kotlin Operator

                Operators are special characters which perform operation on operands (values or variable).There are various kind of operators available in Kotlin.

                • Arithmetic operator
                • Relation operator
                • Assignment operator
                • Unary operator
                • Bitwise operation
                • Logical operator

                Arithmetic Operator

                Arithmetic operators are used to perform basic mathematical operations such as addition (+), subtraction (-), multiplication (*), division (/) etc.

                OperatorDescriptionExpressionTranslate to
                +Additiona+ba.plus(b)
                Subtractiona-ba.minus(b)
                *Multiplya*ba.times(b)
                /Divisiona/ba.div(b)
                %Modulusa%ba.rem(b)

                Example of Arithmetic Operator

                fun main(args : Array<String>) {  
                
                var a=10;  
                
                var b=5;  
                
                println(a+b);  
                
                println(a-b);  
                
                println(a*b);  
                
                println(a/b);  
                
                println(a%b);  
                
                }

                Output:

                15
                5
                50
                2
                0
                

                Relation Operator

                Relation operator shows the relation and compares between operands. Following are the different relational operators:

                OperatorDescriptionExpressionTranslate to
                >greater thana>ba.compateTo(b)>0
                <Less thana<ba.compateTo(b)<0
                >=greater than or equal toa>=ba.compateTo(b)>=0
                <=less than or equal toa<=ba?.equals(b)?:(b===null)
                ==is equal toa==ba?.equals(b)?:(b===null)
                !=not equal toa!=b!(a?.equals(b)?:(b===null))

                Example of Relation Operator

                fun main(args : Array<String>) {  
                
                    val a = 5  
                
                    val b = 10  
                
                    val max = if (a > b) {  
                
                        println("a is greater than b.")  
                
                        a  
                
                    } else{  
                
                        println("b is greater than a.")  
                
                        b  
                
                    }  
                
                    println("max = $max")  
                
                }  

                  Output:

                  b is greater than a.
                  max = 10
                  

                  Assignment operator

                  Assignment operator “=” is used to assign a value to another variable. The assignment of value takes from right to left.

                  OperatorDescriptionExpressionConvert to
                  +=add and assigna+=ba.plusAssign(b)
                  -=subtract and assigna-=ba.minusAssign(b)
                  *=multiply and assigna*=ba.timesAssign(b)
                  /=divide and assigna/=ba.divAssign(b)
                  %=mod and assigna%=ba.remAssign(b)

                  Example of Assignment operator

                  fun main(args : Array<String>) {  
                  
                    
                  
                      var a =20;var b=5  
                  
                      a+=b  
                  
                      println("a+=b :"+ a)  
                  
                      a-=b  
                  
                      println("a-=b :"+ a)  
                  
                      a*=b  
                  
                      println("a*=b :"+ a)  
                  
                      a/=b  
                  
                      println("a/=b :"+ a)  
                  
                      a%=b  
                  
                      println("a%=b :"+ a)  
                  
                    
                  
                  } 

                    Output:

                    a+=b :25
                    a-=b :20
                    a*=b :100
                    a/=b :20
                    a%=b :0
                    

                    Unary Operator

                    Unary operator is used with only single operand. Following are some unary operator given below.

                    OperatorDescriptionExpressionConvert to
                    +unary plus+aa.unaryPlus()
                    unary minus-aa.unaryMinus()
                    ++increment by 1++aa.inc()
                    decrement by 1–aa.dec()
                    !not!aa.not()

                    Example of Unary Operator

                    fun main(args: Array<String>){  
                    
                        var a=10  
                    
                        var b=5  
                    
                        var flag = true  
                    
                        println("+a :"+ +a)  
                    
                        println("-b :"+ -b)  
                    
                        println("++a :"+ ++a)  
                    
                        println("--b :"+ --b)  
                    
                        println("!flag :"+ !flag)  
                    
                    }  

                      Output:

                      +a :10
                      -b :-5
                      ++a :11
                      --b :4
                      !flag :false
                      

                      Logical Operator

                      Logical operators are used to check conditions between operands. List of logical operators are given below.

                      OperatorDescriptionExpressionConvert to
                      &&return true if all expression are true(a>b) && (a>c)(a>b) and (a>c)
                      ||return true if any expression are true(a>b) || (a>c)(a>b) or(a>c)
                      !return complement of expression!aa.not()

                      Example of Logical Operator

                      fun main(args: Array<String>){  
                      
                          var a=10  
                      
                          var b=5  
                      
                          var c=15  
                      
                          var flag = false  
                      
                          var result: Boolean  
                      
                          result = (a>b) && (a>c)  
                      
                          println("(a>b) && (a>c) :"+ result)  
                      
                          result = (a>b) || (a>c)  
                      
                          println("(a>b) || (a>c) :"+ result)  
                      
                          result = !flag  
                      
                          println("!flag :"+ result)  
                      
                        
                      
                      }  

                        Output:

                        (a>b) && (a>c) :false
                        (a>b) || (a>c) :true
                        !flag :true
                        

                        Bitwise Operation

                        In Kotlin, there is not any special bitwise operator. Bitwise operation is done using named function.

                        Named FunctionDescriptionExpression
                        shl (bits)signed shift lefta.shl(b)
                        shr (bits)signed shift righta.shr(b)
                        ushr (bits)unsigned shift righta.ushr(b)
                        and (bits)bitwise anda.and(b)
                        or (bits)bitwise ora.or(b)
                        xor (bits)bitwise xora.xor(b)
                        inv()bitwise inversea.inv()

                        Example of Bitwise Operation

                        fun main(args: Array<String>){  
                        
                            var a=10  
                        
                            var b=2  
                        
                          
                        
                            println("a.shl(b): "+a.shl(b))  
                        
                            println("a.shr(b): "+a.shr(b))  
                        
                            println("a.ushr(b:) "+a.ushr(b))  
                        
                            println("a.and(b): "+a.and(b))  
                        
                            println("a.or(b): "+a.or(b))  
                        
                            println("a.xor(b): "+a.xor(b))  
                        
                            println("a.inv(): "+a.inv())  
                        
                          
                        
                        } 

                          Output:

                          a.shl(b): 40
                          a.shr(b): 2
                          a.ushr(b:) 2
                          a.and(b): 2
                          a.or(b): 10
                          a.xor(b): 8
                          a.inv(): -11
                          
                        1. Kotlin Type Conversion

                          Type conversion is a process in which one data type variable is converted into another data type. In Kotlin, implicit conversion of smaller data type into larger data type is not supported (as it supports in java). For example Int cannot be assigned into Long or Double.

                          In Java

                          int value1 = 10;  
                          
                          long value2 = value1;  //Valid code   

                            In Kotlin

                              var value1 = 10  
                            val value2: Long = value1  //Compile error, type mismatch 

                              However in Kotlin, conversion is done by explicit in which smaller data type is converted into larger data type and vice-versa. This is done by using helper function.

                              var value1 = 10  
                              
                              val value2: Long = value1.toLong()  

                                The list of helper functions used for numeric conversion in Kotlin is given below:

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

                                Kotlin Type Conversion Example

                                Let see an example to convert from Int to Long.

                                fun main(args : Array<String>) {  
                                
                                    var value1 = 100  
                                
                                    val value2: Long =value1.toLong()  
                                
                                    println(value2)  
                                
                                } 

                                  We can also converse from larger data type to smaller data type.

                                  fun main(args : Array<String>) {  
                                  
                                      var value1: Long = 200  
                                  
                                      val value2: Int =value1.toInt()  
                                  
                                      println(value2)  
                                  
                                  }
                                1. Kotlin Data Type

                                  Data type (basic type) refers to type and size of data associated with variables and functions. Data type is used for declaration of memory location of variable which determines the features of data.

                                  In Kotlin, everything is an object, which means we can call member function and properties on any variable.

                                  Kotlin built in data type are categorized as following different categories:

                                  • Number
                                  • Character
                                  • Boolean
                                  • Array
                                  • String

                                  Number Types

                                  Number types of data are those which hold only number type data variables. It is further categorized into different Integer and Floating point.

                                  Data TypeBit Width (Size)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

                                  Character (Char) Data Type

                                  Characters are represented using the keyword Char. Char types are declared using single quotes (”).

                                  Data TypeBit Width (Size)Data Range
                                  Char4 bit-128 to 127

                                  Example

                                  val value1 = 'A'  
                                  
                                  //or  
                                  
                                  val  value2: Char  
                                  
                                  value2= 'A'  

                                    Boolean Data Types

                                    Boolean data is represented using the type Boolean. It contains values either true or false.

                                    Data TypeBit Width (Size)Data Value
                                    Boolean1 bittrue or false

                                    Example

                                    1. val flag = true  

                                    Array

                                    Arrays in Kotlin are represented by the Array class. Arrays are created using library function arrayOf() and Array() constructor. Array has get (), set() function, size property as well as some other useful member functions.

                                    Creating Array using library function arrayOf()

                                    The arrayOf() function creates array of wrapper types. The item value are passed inside arrayOf() function like arrayOf(1,2,3) which creates an array[1,2,3].

                                    The elements of array are accessed through their index values (array[index]). Array index are start from zero.

                                    val id = arrayOf(1,2,3,4,5)  
                                    
                                    val firstId = id[0]  
                                    
                                    val lasted = id[id.size-1] 

                                      Creating Array using Array() constructor

                                      Creating array using Array() constructor takes two arguments in Array() constructor:

                                      1. First argument as a size of array, and
                                      2. Second argument as the function, which is used to initialize and return the value of array element given its index.
                                      val asc = Array(5, { i -> i * 2 }) //asc[0,2,4,6,8]  

                                        String

                                        String in Kotlin is represented by String class. String is immutable, which means we cannot change the elements in String.

                                        String declaration:

                                        val text ="Hello, JavaTpoint"  

                                        Types of String

                                        String are categorize into two types. These are:

                                        1. Escaped String: Escape String is declared within double quote (” “) and may contain escape characters like ‘\n’, ‘\t’, ‘\b’ etc.

                                        val text1 ="Hello, JavaTpoint"  
                                        
                                        //or  
                                        
                                        val text2 ="Hello, JavaTpoint\n"  
                                        
                                        //or  
                                        
                                        val text3 ="Hello, \nJavaTpoint" 

                                          2. Raw String: Row String is declared within triple quote (“”” “””). It provides facility to declare String in new lines and contain multiple lines. Row String cannot contain any escape character.

                                          val text1 ="""  
                                          
                                                       Welcome   
                                          
                                                           To  
                                          
                                                     JavaTpoint  
                                          
                                              """
                                        1. Kotlin Variable

                                          Variable refers to a memory location. It is used to store data. The data of variable can be changed and reused depending on condition or on information passed to the program.

                                          Variable Declaration

                                          Kotlin variable is declared using keyword var and val.

                                          var language ="Java"  
                                          
                                          val salary = 30000

                                          The difference between var and val is specified later on this page.

                                          Here, variable language is String type and variable salary is Int type. We don’t require specifying the type of variable explicitly. Kotlin complier knows this by initilizer expression (“Java” is a String and 30000 is an Int value). This is called type inference in programming.

                                          We can also explicitly specify the type of variable while declaring it.

                                          var language: String ="Java"  
                                          
                                          val salary: Int = 30000 

                                            It is not necessary to initialize variable at the time of its declaration. Variable can be initialized later on when the program is executed.

                                            var language: String  
                                            
                                            ... ... ...  
                                            
                                            language = "Java"  
                                            
                                            val salary: Int  
                                            
                                            ... ... ...  
                                            
                                            salary = 30000  

                                              Difference between var and val

                                              • var (Mutable variable): We can change the value of variable declared using var keyword later in the program.
                                              • val (Immutable variable): We cannot change the value of variable which is declared using val keyword.

                                              Example

                                              var salary = 30000  
                                              
                                              salary = 40000 //execute  

                                                Here, the value of variable salary can be changed (from 30000 to 40000) because variable salary is declared using var keyword.

                                                val language = "Java"  
                                                
                                                language = "Kotlin" //Error  

                                                  Here, we cannot re-assign the variable language from “Java” to “Kotlin” because the variable is declared using val keyword.

                                                1. Kotlin First Program Printing ‘HelloWorld’

                                                  Let’s create a Kotlin first example using IntelliJ IDEA IDE.

                                                  Steps to Create First Example

                                                  1. Open IntelliJ IDEA and click on Create New Project’.

                                                  Kotlin First Program IDE

                                                  2. Select Java option, provide project SDK path and mark check on Kotlin/JVM frameworks.

                                                  Kotlin First Program IDE 1

                                                  3. Provide the project details in new frame and click ‘Finish’.

                                                  Kotlin First Program IDE 2

                                                  4. Create a new Kotlin file to run Kotlin first example. Go to src ->New->Kotlin File/Class.

                                                  Kotlin First Program IDE 3

                                                  5. Enter the file name ‘HelloWorld’ and click ‘OK’.

                                                  Kotlin First Program IDE 4

                                                  6. Write the following code in ‘HelloWorld.kt’ file. Kotlin files and classes are saved with “.kt” extension.

                                                  fun main(args: Array<String>) {  
                                                  
                                                      println("Hello World!")  
                                                  
                                                  }  

                                                    We will discuss the detail of this code later in upcoming tutorial.

                                                    Kotlin First Program IDE 5

                                                    7. Now we can run this program by right clicking on file and select Run option.

                                                    Kotlin First Program IDE 6

                                                    8. Finally, we got the output of program on console, displaying ‘HelloWorld’ message.

                                                    Kotlin First Program IDE 7
                                                  1. Kotlin Environment Setup (IDE)

                                                    Install JDK and Setup JDK path

                                                    Since, Kotlin runs on JVM, it is necessary to install JDK and setup the JDK and JRE path in local system environment variable. Use this link https://www.javatpoint.com/how-to-set-path-in-java to setup JDK path.

                                                    Install IDE for Kotlin

                                                    There are various Java IDE available which supports Kotlin project development. We can choose these IDE according to our compatibility. The download links of these IDE’s are given below.

                                                    IDE NameDownload links
                                                    IntelliJ IDEAhttps://www.jetbrains.com/idea/download/
                                                    Android Studiohttps://developer.android.com/studio/preview/index.html
                                                    Eclipsehttps://www.eclipse.org/downloads/

                                                    In this tutorial, we are going to use IntelliJ IDEA for our Kotlin program development.

                                                    Steps to Setup IntelliJ IDEA

                                                    1. Download IntelliJ IDEA.

                                                    Kotlin Environment Setup IDE

                                                    2. Run the downloaded setup.

                                                    Kotlin Environment Setup IDE 1

                                                    3. Click next to continue.

                                                    Kotlin Environment Setup IDE 2

                                                    4. Choose installation location.

                                                    Kotlin Environment Setup IDE 3

                                                    5. Choose start menu folder and click Install.

                                                    Kotlin Environment Setup IDE 4

                                                    6. Click Finish to complete Installation.

                                                    Kotlin Environment Setup IDE 5
                                                  2. Kotlin First Program Concept

                                                    Let’s understand the concepts and keywords of Kotlin program ‘Hello World.kt’.

                                                    fun main(args: Array<String>) {  
                                                    
                                                        println("Hello World!")  
                                                    
                                                    } 

                                                      1. The first line of program defines a function called main(). In Kotlin, function is a group of statements that performs a group of tasks. Functions start with a keyword fun followed by function name (main in this case).

                                                      The main () function takes an array of string (Array<String>) as a parameter and returns Unit. Unit is used to indicate the function and does not return any value (void as in Java). Declaring Unit is an optional, we do not declare it explicitly.

                                                      fun main(args: Array<String>): Unit {  
                                                      
                                                      //  
                                                      
                                                      } 

                                                        The main() function is the entry point of the program, it is called first when Kotlin program starts execution.

                                                        2. The second line used to print a String “Hello World!”. To print standard output we use wrapper println() over standard Java library functions (System.out.println()).

                                                        println("Hello World!")  

                                                        Note: Semicolons are optional in Kotlin.

                                                      1. Kotlin Hello World Program in Command line.

                                                        To write Kotlin program, we can use any text editor like: Notepad++. Put the following code into any text file and save.

                                                        fun main(args: Array<String>){  
                                                        
                                                            println("Hello World!")  
                                                        
                                                        } 

                                                          Save the file with name hello.kt, .kt extension is used for Kotlin file.

                                                          Compile Kotlin File

                                                          Open command prompt and go to directory location where file is stored. Compile hello.kt file with following command.

                                                          kotlinc hello.kt -include-runtime -d hello.jar  
                                                          Kotlin Hello World Program in Command line 1

                                                          Run Kotlin File

                                                          To run the Kotlin .jar (hello.jar) file run the following command.

                                                          java -jar hello.jar  
                                                          Kotlin Hello World Program in Command line 2