Kotlin: A better successor to Java

It has been almost a year since Google officially announced Kotlin for Android in its I/O conference of 2017.  Though Kotlin is not a widely known programming language, it is currently on the roll; and developers are vigorously choosing Kotlin over Java for app development.

Kotlin is a statically typed programming language and is used by developers to develop Java, Android, JS browser and native applications. It is developed by JetBrains and is easily interoperable with Java and Android. Kotlin follows object-oriented approach, similar to Java.

But, it seems to be a better option than Java as it offers cleaner syntax scheme, a simpler code file and different functional elements that Java does not have, till date. Some features that are unique to Kotlin are Null Safety, Lambda expressions, Companion Objects, and Getters & Setters, etc.

Kotlin has become quite popular after Google I/O 2017 conference.

In a research by Realm, it was found that the adoption rate of Kotlin, in the year following Google’ s official announcement, went from 7.4% to 14.7%.

Well, looking at the number of developers switching to Kotlin, it can be predicted that it might surpass the ones working with Java.

Let us now explore why developers are switching to Kotlin for android application:

1. Java Inter-Operability:

Kotlin is 100% interoperable with Java. Therefore, developers can easily use Kotlin to work on their old Java projects. There are several Java Frameworks, which implies that anything written in Kotlin will be accepted by all the frameworks.

2. Almost same syntax :

The syntax followed in Kotlin is in accordance with OOP. This can be easily understood by any programmer coming from the OOP domain. It has some variations from Java, for instance, the constructors have been reworked along with the val var variable declarations. Check the snippet below

class Foo {

    val b: String = "b"     // val means unmodifiable
    var i: Int = 0          // var means modifiable

    fun hello() {
        val str = "Hello"
        print("$str World")
    }

    fun sum(x: Int, y: Int): Int {
        return x + y
    }

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

}

3. String Interpolation

Java’s String.format () is available in Kotlin with a much better and more readable version. Let’s have a look at the snippet below:

val x = 4
val y = 7
print("sum of $x and $y is ${x + y}")  // sum of 4 and 7 is 11

4. Casts made Smarter:

The Kotlin compiler is smart and automatically tracks the logic & auto-casts types if possible. This means no more instanceof checks followed by explicit casts:

if (obj is String) {
    print(obj.toUpperCase())     // obj is now known to be a String
}

5. Equal operator:

The ==operator checks for the structural quality, where the explicit call to equals() can be avoided.

val john1 = Person("John")
val john2 = Person("John")
john1 == john2    // true  (structural equality)
john1 === john2   // false (referential equality)

6.Default Arguments

Kotlin allows the users to use the default arguments, thereby, can avoid defining several similar methods. Just look at the below snippet:

fun build(title: String, width: Int = 800, height: Int = 600) {
    Frame(title, width, height)
}

7. Named Arguments

Builders are no more needed in Kotlin, because the named arguments when combined with default arguments fulfills the need of the builders.

build("PacMan", 400, 300)                           // equivalent
build(title = "PacMan", width = 400, height = 300)  // equivalent
build(width = 400, height = 300, title = "PacMan")  // equivalent

8. When Expression

There is no “switch case” in Kotlin as it has been replaced by the when expression. While comparing the when expression with switch, “when” has got somewhat similar functionality as switch. In when expression, every case is evaluated in a sequential manner until a condition is satisfied, and if none of the conditions is satisfied, then else case is returned.

when (x) {
    1 -> print("x is 1")
    2 -> print("x is 2")
    3, 4 -> print("x is 3 or 4")
    in 5..10 -> print("x is 5, 6, 7, 8, 9, or 10")
    else -> print("x is out of range")
}

It can be used both as expression or statement, with or without an argument.

val res: Boolean = when {
    obj == null -> false
    obj is String -> true
    else -> throw IllegalStateException()
}

9. Properties

There are no fields in Kotlin like Java, but if there is any variable created, then they are properties by default. The custom get & set can be directly accessed with the help of variable by simply using (.) operator.

class Frame {
    var width: Int = 800
    var height: Int = 600

    val pixels: Int
        get() = width * height
}

10. Data Class

Classes are commonly used to describe data and instances associated with instances of that class. Kotlin offers a better solution than the usual classes defined in Java. It is called Data Class. It is like a normal class with some additional features. The data classes allow you to avoid writing the lengthy code. Here, the compiler automatically derives the implementation of standard methods like equals (), hashcode (), toString () and copy () from the properties declared in the primary constructor of data class. Unlike Java, it does not take up 100 lines of code.

data class Person(val name: String,
                  var email: String,
                  var age: Int)

val john = Person("John", "john@gmail.com", 112)

11. Operator overloading

Kotlin offers a predefined set of operators which have fixed symbolic representation and fixed precedence.  For implementing an operator, either a member function or an extension function is provided with a fixed name for the corresponding type for unary ones. An operator modifier is needed to mark the functions that overload operators.

data class Vec(val x: Float, val y: Float) {
    operator fun plus(v: Vec) = Vec(x + v.x, y + v.y)
}

val v = Vec(2f, 3f) + Vec(4f, 1f)

12. Destructuring declarations

Kotlin allows destructuring an object into number of variables. For instance,

val (name, age) = person 

This is known as a destructuring declaration, which creates multiple variables at a time. In the above example, two new variables are declared: name and age, which can be used independently like the following:

println(name)

println(age)

A destructuring declaration is compiled down as follows:

val name = person.component1()

val age = person.component2()

13. Ranges

Range expression is basically defined for any comparable type and consists of rangeTo functions with an operator form ..which is complemented by in and !in.

Example,

if (i in 1..10) { // equivalent of 1 <= i && i <= 10

    println(i)

}

Integral type ranges such as IntRange, LongRange, CharRange have an extra feature that they can be iterated over. This means that compiler analogously converts this to Java’s indexed for loop, without creating any extra overhead.

for (i in 1..4) print(i) // prints "1234"

If someone wishes to iterate the numbers in reverse order, then downTo() function defined in the standard library can be used.

for (i in 4 downTo 1) print(i) // prints "4321

14. Extensions

Kotlin allows the user to extend a class with new functionalities without the need to inherit from the class. This can be done with the help of special declarations known as extensions. The language supports extension functions and extension properties. Let us understand it with the help of an example.

Here, we have added swap function to the MutableList<Int>. The this keyword inside the extension function corresponds directly to the receiver object. The receiver object is the one which is added after the dot. Now, such function can be easily called on any MutableList<Int> like the following.

15.  Lambda expressions

Lambdas are code blocks enclosed in the curly braces. The syntax is as follows:

val sum = { x: Int, y: Int -> x + y }

16. IDE Support

Any framework which is easily compatible with Java can be compatible with Kotlin, as it is interoperable with Java.

Conclusion

Kotlin is an open source project under Apache 2.0.  It is modern, expressive, and safe with enhanced readability and has extended functionality. Developers find it easy to work with Kotlin.

We hope Kotlin will prove to be a better programming language for the Android developers and we are really excited to see it evolving. If you wish to share your views on the budding language, comment below.

Avatar for Multidots
Author : Multidots
Multidots is full service enterprise software development company with services revolving around consulting, enterprise-grade custom application development, custom mobile and cloud applications to automated and manual testing. We are proud to have served mid-sized to large enterprises including Fortune 500 Companies in our clientele.

Comments

1 Comment

  • Avatar for Multidots
    priya

    Java and .NET are fundamentally quite similar. Both are intended to simplify the development of apps by providing a system of modular, standardized components and services. Many thanks for sharing this.

Leave a Reply

How can we help you?

Submit your Business Enquiry here and we will get in touch shortly.

Contact Us

Looking for a First-Class Technology Consultant?

X

Quick Contact

I give my consent to the storage and processing of my personal data by Multidots as per their privacy policy compliance.