Introduction of Kotlin

  • By
  • August 27, 2019
  • JAVA Programming
Introduction of Kotlin

Introduction of Kotlin

Kotlin is a new statically typed , open source programming language, which acquires features from other languages like, Java, Groovy, Scala etc. Kotlin fisrt appeared in 2011. Kotlin v1.0 , v1.2, v1.3 was released on 15 February 2016 , 28 November2017 and 29 October2018 respectively. Resent stable release is Kotlin v1.3.41 on 3rd July 2019 .i.e. few days ago. The name Kotlin came from kotlin island which is a Russian Island located near gulf of Finland, st Petersburg. Kotlin is designed and developed by JetBrains and development lead Andrey Breslav said that, kotlin is designed to be better than java which has industrial strength of object oriented programming language. JetBrains is a software development company, which also have developed IDE for Google’s Android Operating System i.e. Android studio. Jet Brains have developed many software development tools as well like Intellij IDEA, PyCharm, TeamCity, WebStrosm, GoLand, RubyMine etc.

For Free Demo classes Call: 8237077325
Registration Link: Click Here!

Brevity Of Kotlin

Readability
Kotlin is more readable. Kotlin support object oriented programming so code looks similar to java. Kotlin has well defined function types, which helps us to understand the flow easily. One kotlin example is given in next point for performing arithmetic operation. You will be able to understand the code even if you have very less programming background. Which shows that kotlin is more readable, simple language.

Concise code
Kotlin gives the lot of information clearly and in few words , so the number of lines of the program automatically gets reduced. Following example gives us the difference between a java code and kotlin code. In this example we have written a function which performs arithmetic operation based on the user’s requirement. Calculate is parameterised function which accepts 3 arguments double, String and double.

// demo.kt file   i.e Kotlin code

fun  calculate (a: Double, op: String, b: Double): Double {

    when (op) {

            “add” -> return a + b

            “subtract” -> return a – b

            “multiply” -> return a * b

            “divide” -> return a / b

            else -> throw Exception()

        }

    }

fun main(args: Array<String>) {

    calculate(10.5,“add”,20.5)

    println(“Result is  :”+calculate(10.5,“add”,20.5))

}

// Same code in java with Demo.java file

public class Demo {

    public static void main(String[] args) {

        System.out.println(” Result : “+calculate(20,“add”,30));

    }

    public static double calculate(double n1,String op,double n2) {

        if(op.equals(“add”)){

            return (n1+n2);

        }else if(op.equals(“sub”)){

            return (n1-n2);

        }else if(op.equals(“multiply”)){

            return (n1*n2);

        }else if(op.equals(“div”)){

            return (n1/n2);

        }else{

            try {

                throw new Exception();

            } catch (Exception e) {

                System.out.println(“Exception”);

            }

            return 0;

        }

   }

}

For Free Demo classes Call: 8237077325
Registration Link: Click Here!

Reduced boiler plate code
Boiler plate code is the code which have to be included in many places with little or no alteration. If you want to create two Fragments with similar kind of structure, you will have to create Two classes as shown below.

//PageOne.java

public class PageOne extends Fragment {

    public static PageOne newInstance(String s1) {

        PageOne obOne = new PageOne();

        Bundle bundle = new Bundle();

        bundle.putString(“paheOneId”, s1);

        obOne.setArguments(bundle);

        return obOne;

    }

}

//PageTwo.java

public class PageTwo extends Fragment {

    public static PageTwo newInstance(String s2) {

        PageTwo ob2 = new PageTwo();

        Bundle bundle = new Bundle();

        bundle.putString(“pageTwoID”, s2);

        ob2.setArguments(bundle);

        return ob2;

    }

}

If you wish to do same code using Kotlin , the code will get reduced. Kotlin removes the boilerplate code as shown below. To reduce duplication, in the following code I have used  “ withArgs {“ . To learn use of “apply” or “ withArgs” you will have to go through the kotlin language details. But as the kotlin is more readable language , you will surely get an idea of what exactly we are doing in the following example. 

class PageOne: Fragment() {

companion object {

fun newInstance(Page2data: String) = PageOne().withArgs {

putS/tring(“Page2data”, Page2data  }  } }

class PageTwo: Fragment() {

companion object {

fun newInstance(Page1data: String) = PageTwo().withArgs {

putString(“Page1data”, Page1data) }  }}

For Free Demo classes Call: 8237077325
Registration Link: Click Here!

Inter-operable and null Safe
             Java is meant for Inter-portability. We can compile kotlin code with Java. Kotlin produces byte-code , so we can easily run kotlin programs on JVM. As the compiler of kotlin produces byte-code, we can use kotlin in combination with java for project development, which a great feature.

Java and android uses null value to represent ‘no value’. But, a null value can destroy the app. This problem is solved in kotlin. Kotlin provides safe null call as shown bellow.

            var a : String = null

            print(a.length)     // Gives compile time error

            var  a = “SevenMentor Pvt Ltd.”

              print(a?.length) //prints 20

No Primitive data types No Compile time Exception
            Primitive data types are great for backward compatibility but can also throw exception while type casting that too while execution. We don’t have solution to avoid such ClassCastException in Java. As kotlin does not have primitive data types , becomes more type safe and avoids ClassCastException. Also, Java provides auto typecasting i.e. implicit typecasting. While working with kotlin we have to do everything explicitly. We need to use specific functions  as shown below.

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

//java code

int num1 = 101;

long num2 = num1; //implicit typecasting

//kotlin code

val num1: Int = 10

val num2: Long = num1 // error, type mismatch

 val num1: Int = 10

val num2: Long = num1.toLong() // works fine

For Free Demo classes Call: 8237077325
Registration Link: Click Here!

 Expressive Language
           To have a bean class in Java we have to first declare instance variable then constructor and getter-setter, which all together creates a large code. But, In Kotlin it is reduced ans its so simple to  understand. But you should have goods core java knowledge. In the bellow example we can observe that 57 lines of code can be reduced to 7 line if we use kotline data class. Kotlin data class gives inbuilt implementation of  toString() , hashCode(), copy() methods.

// Student.java

public class Student {

    private int id;

    private String sname;

    private String course;

    private int admissionYear;

    public Student(int id, String sname, String course, int admissionYear) {

        this.id = id;

        this.sname = sname;

        this.course = course;

        this.admissionYear = admissionYear;

    }

    public int getId() {

        return id;

    }

    public void setId(int id) {

        this.id = id;

    }

    public String getSname() {

        return sname;

    }

    public void setSname(String sname) {

        this.sname = sname;

    }

    public String getCourse() {

        return course;

    }

    public void setCourse(String course) {

        this.course = course;

    }

    public int getAdmissionYear() {

        return admissionYear;

    }

    public void setAdmissionYear(int admissionYear) {

        this.admissionYear = admissionYear;

    }

@Override

public String toString() {

return “Student{” +

“id=” + id +

“, sname='” + sname + \’+

“, course='” + course + \’+

“, admissionYear=” + admissionYear +

‘}’;

}

       }

      // Student.kt

data class Student (

    var id : Long,

    var name : String,

    var course :String,

    var admissionYear : Long

)

For Free Demo classes Call: 8237077325
Registration Link: Click Here!

Extension Functions
           We can extends functionality of a classes by using extension functions. We can define the function separately and can call them whenever needed. Example is shown bellow.

fun String.funTwo(): String=this.replace(“Java” ,“Kotlin”)

fun main(args: Array<String>) {

    val myString= “Hello Everyone..!! Welcome to Java class.\n+

            “Java is Object Oriented Programming language. \nWe should learn Java from the best Java Classes In Pune

    val result = myString.funTwo()

    println(“Result is :\n $result)

}

o/p :

Result is :

Output

Hello Everyone..!! Welcome to Kotlin class. Kotlin is Object Oriented Programming language.
We should learn Kotlin from the best Java Course In Pune.


For Free Demo classes Call: 8237077325
Registration Link: Click Here!

What all ways we can use Kotlin ?

  • Combining Java And Kotline for a Project is possible
    We can use combination of java and kotlin language develop a project. All the kotlin files are saved with .kt extension and can be compiled with JVM to produce byte code. So, we can have combination of kotlin and java files in a project.
  • Kotlin For android
    Android Studio is Official IDE for Androi which was published in 2013. Android studio has been implemented as plugin over IntelliJ IDEA, which is a Java IDE created by JetBrains. All the activities which you will create , you can directly convert them to kotlin files. For Android studio which is bellow version 2.3 , we need to install android plugins explicitly.
  • Kotlin for web application and Spring Boot Applications
    We can use kotlin to create a web application as well as to create a Spring Boot Application. To develop a web application or a J2EE application basically we need a web.xml file and a servlet. Kotlin provides us the servlet but with much reduced code. We can use Tomcat to have servlet container to execute a web application. So, Tomcat’s servlet container will read the web.xml file and will support the kotlin servlet. Kotlin servlet will accept the request coming from client and will response back to the client , with the html code , which will execute with web browser. Bellow code is example of servlet in kotlin, to create a web application.

// ServletOne.kt

import javax.servlet.annotation.WebServlet

import javax.servlet.http.HttpServlet

import javax.servlet.http.HttpServletRequest

import javax.servlet.http.HttpServletResponse

@WebServlet(name = “Home”, value = “/hello”)

class MyServlet : HttpServlet() {

    override fun doGet(req: HttpServletRequest, res: HttpServletResponse) {

        res.writer.write(“Hello, World!”)

        res.setContentType(“text/html”)

        val out = res.getWriter()

        out.print(“<html><body>”)

        out.print(“<h3>Seven Mentor Kotlin Example by Sonali</h3>”)

        out.print(“<h4>Servlet App Using Kotlin</h4>”)

        out.print(“</body></html>”)

    }

}

  • JavaScript and kotlin
    Few things which states that we should use kotlin with JavaScript are
  1. Kotlin JS can be called as awsome as almost all features from java script are available with kotlin
  2. In combination with Kotlin JS we can use Jquery , Java Script.
  3. Server side Code can be reused
  4. Kotlin JS provides great IDE i.e. IntelliJ. For Java Script we generally use Notepad++. For a developer writing code with Notepad++ is nothing great. Kotlin JS uses IntelliJ which gives you great features. We should surely try once.

For Free Demo classes Call: 8237077325
Registration Link: Click Here!

Major Industry Benefits of Kotlin use for Project Development

  • Less Software crashes
  • Reduced time required for Project development
  • Reduced Project complexity.

Kotlin vs Java

Kotlin

Java is open source programming language which has vast use, also java has huge predefined library . Still as we know know language is perfect in the software world, java is complex language, so developers may find java as boring or dull. Kotlin resolves complexity of java program in a much better way and improves the entire programming structure.

Some of the expert say that kotlin will overcome java. Other experts are saying that kotlin and java together will make a strong hold on  the software field. Maximum of them are agreed that kotlin is a strong language, with less complexity ans more readability. So basically Kotlin improves existing structure of java.

Questions And Queries?

Question mark Icon

We will come back to you again with next blog at Java Training In Pune which will include more details about kotlin language like Inheritance, typecasting etc. Still if you have any queries feel free to ask.
Happy to Help you..!!

Call the Trainer and Book your free demo Class for JAVA now!!!

call icon

 

Submit Comment

Your email address will not be published. Required fields are marked *

*
*