Kotlin(The New Alternative to Java)

kotlin java
Kotlin

If you have been a follower of Google IO, which is Google’s annual developers event for showcasing their new stuffs and improvements, then you must have heard of Kotlin announced as the third language to have joined the Android platform(after C/C++ and Java) kotlin java.

What the  is Kotlin?

Each and everyday, new languages popup from here and there leaving us with arguments that will popup like “this or that is the best language”.Kotlin is one of those languages that has shown up.But what is it?

In a simple sentence, Kotlin is a statically typed JVM language developed by Jetbrains which is also responsible for creation of the best Integrated Development Environments(IDEs) (if not the best for you) such as IntelliJ,Android Studio,Pycharm and many other tools. It is Object Oriented as well as functional.

Some people consider Kotlin as a replacement for Java but I don’t see it that way.Kotlin code compiles to Java before running on the JVM.

Why should you, being a Java developer or new Developer choose Kotlin?

This article’s aim is to show you some of the advantages that Kotlin presents and to show you some code samples. I will present the advantages first then the code samples later.

  • Interoperality with Java

Kotlin is totally interoperable with Java. What does this mean? This means you can call Java code within Kotlin and also you can call Kotlin code in Java. This enables a developer to be able to mix code(for a reason I can’t really explan). We haven’t written any Kotlin code yet.Before we see interoperabilty, let us see a hello world Kotlin example.

/** HelloWorld.kt **/

/**Main method where Kotlin code starts execution**/
fun main(args:Array<String>)
{
  println("Hello Kt World")
}

The code is similar to Java but with some differences such as the optional use of semicolons. Essentially the HelloWorld.kt file has a main method that takes an array of Strings as argument(note how it differs from Java’s way.)

Back to interoperability. Let us see how we can call Java code within Kotlin usng the Java class Student below.

public class Student {
    private String firstName;
    private String lastName;
    private int studentId;

    public Student(String firstName, String lastName, int studentId) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.studentId = studentId;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int getStudentId() {
        return studentId;
    }

    public void setStudentId(int studentId) {
        this.studentId = studentId;
    }
}

Now let us see how in Interop.kt(Kotlin files end in .kt), we can create and manipulate a Student object.

/**InterOp.kt**/
fun main(args: Array<String>) {
    var student:Student = Student("Ngenge","Senior",1234)

    /** Print first name**/
    println(student.getFirstName())
    println(student.firstName)
}

Funny enough, the above code compiles. But note another thing.The two lines of code do the same thing. But the preferred way is accessing properties(i.e student.firstName) in Kotlin.

  • Expressiveness

One notable thing about Java(and of course other languages) is the creation of data classes with getters and setters and toString methods.But with Kotlin, there is no need for such boilerplate code as the language autogenerates accessors and other methods like toString for you. The above Student class which will be more than 40 lines in Java of code can be written in Kotlin in less than 10 lines.

data class Student(private var firstName:String,
                        private var lastName:String,
                        private var studentId:Int )

Funny enough, this class is the equivalent of the Student.java class above.It has default accessors and toString. Just imagine three lnes of code replacing more than forty lines of code(this is just awesome).Write more with less code.So to access the firstName for a Student object in Kotlin, all you do is using the convention object.firstName and to assign a new firstName, all you do is object.firstName = “New Name”

  • Null safety

If you have some experience with Java, you must have dealt with some NullPointerException issues. Well Kotlin is null safe, that is objects cannot take null values except you state that they can take null values.

/** This will not compile as Student cannot be null*/
var student:Student = null

/**This will compile.student can be null**/
var student:Student? = null
  • Kotlin is Functional

Though Kotlin is object oriented, it is functional as well.If you are new to functional programming, here are the key concepts of functional programming;

  1. Notion of First-class Functions where functions are seen as values and functions can be assigned as variables, passed as parameters to other functions and functions can be returned from other functions.

  2. Immutability where state of objects cannot be changed after their creation.

  3. No side effects:Pure functions are used that will return same results each time the same inputs are provided and do not modify the state of other objects or interact with the outside world.

The advantages of functional programming are safe multithreading and easier testing.Errors usually occur in multithreaded programs where a piece of data is modified from multiple sources without proper synchronisation.But proper data structures and pure functions will help avoid this.It is easier to test code without side effects.

4.  Kotlin is Open Source
Kotlin tools, libraries,compiler are open source,available under an Apache2 license.You can always check theKotlin repo.

Before the article draws to a conclusion, let us check some code samples.

Functions

/**
 * Functon takes integers x and y with a return type of Int
 */
fun multiply(x:Int,y:Int):Int{
    return x * y
}
/** No need or braces when only one statement is necessary**/

fun add(x: Int, y: Int):Int  = x + y

/** Kotlin will know that return type is Int**/

fun subtract(x: Int,y: Int) = x - y

/*Find the max of a and b.
* Note here that if construct is an epression in Kotlin(returns a value)
* unlike in Java
*/

fun max(a:Float,b:Float) = if(a>b) a else b

There is more that can be done wth functions but let it be left as a todo for anyone interested in Kotlin.

String formatting with templates
Check the function below and let us understand what string templates are

```java
/**StringTemplates.kt
*
**/
fun add(x:Int,b:Int)
{
println("$a + $b = ${a+b}")
}

Calling the above function with 2 and 3 prints “2 + 3 = 5”. This is more compact and efficient compared to concatenation in Java.To display a simple variable in a string, all that has to be done is placing a “$” attached to the variable. But complex expressions are evaluated this way but with the expression placed within braces({}).

Mutables and immutables
Variables declared with val(from value) are immutable(cannot be reassigned after initialisation) while those declared with var(from variable) are mutable.

Properties
In Java(and other OOP languages) data is usually stored and private fields.Clients access such fields using only accessor methods.

class Student{
private String name;

public void setName(String name){
this.name = name;
}

public String getName()
{
  return this.name;
}
}

In Kotlin however,properties are a first class feature and replaces fields and accessors. A property is declared same way as a variable with either val or var keyword.Properties declared with var are writable, that and a field,getter and setter are generated for it while val properties are read-only(field and getter generated). So a Person class in Kotlin will be defined as follows,

class Person(
val:name:String,
val isCameroonian:Boolean
)
 fun main(args:Array<String>){
 val person = Person("Jackson",true)
 /**Prints Jackson**/
 println(person.name)
 
 /**Prints true**/
 println(person.isCameroonian)
 }

There is a lot that about Kotlin that cannot be shown in a single article. So do well to dive into it if you are interested.

Conclusion

Kotlin is a language that any programmer will want to learn give its cool features and if it wasn’t mentioned, it runs on the server and Android as well as other platforms. Kotlin is here to solve problem as it is a language not meant for research but it is for solving problems. It is a combination of language features that have been proven as worthy of a language. So you can start learning Kotlin today.

Learn how to build Cross platform Modern Mobile apps using first class architectural design patterns with reactive ui Here.

Quicklinks

Kotlin repository
Kotlin reference
Try Kotlin Online
Kotlin Blog

Follow me on social media and stay updated

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.