Moving to Kotlin

Hi folks,
This will be my first story at this platform, so it may sound amateurishly crafted and too excited, apologies in advance, appreciating all comments and suggestions 😃
Until Google IO 17, I'd go on with Java if I am going to starting a new Android project or adding new feature to an existing one, but from now on I will totally concentrate toward Kotlin.

I will be trying to explain why Kotlin should be the following programming language you have to definitely discover, let's start slowly.

For the firs-time hearers, Kotlin is statically typed programming language created by JetBrains whom we already know from the awesome IDEs Android Studio, IntelliJ and ReSharper. Although the general usage of the language is with developing Android apps (since it compiles to JVM), there are several usage areas can be considered like developing front-end apps, and iOS 😱 maybe… I am going to stick to Java & Kotlin. Let's check the titles which I'll be detailing:

  • Concise
  • Safe 👷
  • Versatile

Concise

We are all familiar with Boilerplate code that the  draining code blocks we have to write and can be copy/paste (ie. encapsulator methods in Java)

I can easily say for most of the developers, the ultimate aim is to minimize these code (cause we're lazy!!!), so Kotlin tries to do this for Java gratefully. Well not only for Java but as a programming language it tries to do so.

Let's try to give a deep example for what I've just mentioned:
I'm going to implement the User class that also implemented in thousands of examples:

public final class User {
  @NotNull
  private final String name;
  private final int age;
  
  User(@NotNull String name, int age) {
    super();
    if (name == null) {
      throw new RuntimeException("Name can't be null");
    }
    this.name = name;
    this.age = age;
  }
  @NotNull
  public final String getName() {
    return this.name;
  }
  public final int getAge() {
    return this.age;
  }
  public int hashCode() {
    return "User(name=" + this.name + ", age=" + this.age + ")";
  }
  public boolean equals(Object otherObject) {
    if(this != otherObject) {
      if(otherObject instanceof User) {
        User otherUser = (User) otherObject;
        return this.name.equals(otherUser.name)
          && this.age == otherUser.age;
      }
      return false;
    } else {
      return true;
    }
  }
}

It nearly contains all of the components a data object should have and took 36 lines to define.
If we implement same class with Kotlin:

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

😱😱😱 We can simply do that with one line, "data class" type combines all of the encapsulator, hashCode, and equals methods which Java version holds.

## Safe Before starting to neat parts that help safe coding, I'd like to explain few things.

The Billion $ Mistake: Tony Hoare included null references into our lives when programming something related to object-oriented at 1965, and apologizes for the stresses and disasters that he couldn't help himself to implement null, because it was too easy for his achievement.

The NullPointerException or pain in the neck or NPE for short, this annoyance basically happens when you try to access a null reference. I have heard this or similar named error from all of the languages that I experienced that thrown when you try to reach a null reference of an object or method.

In Kotlin, the type system identifies among references that can be nullable and those that can not (non-null references). For example, a regular variable of type String cannot hold null:

Note: Similar to Swift's (?) optional, Kotlin also uses the question mark (?) for nullable and double exclamation mark non-null (!!)*

In compile time, Kotlin yells to var/val definitions for possible null mistakes like in below example:

var s: String = "wow"
s = null                // compile error
var h: String? = "hots"
h = null                // no problem
val i = h.length        // compile error: b might be null
If we need to stop compiler complaining about "might be null" for above example, we can use following lines:
if (h == null) return
val i = h.length        // no problem
Or we can simply use safe call (?.) which is shorter 👀 👀
val i = h?.length       // type of i is nullable Int

What safe call does and I think it's the best feature I've ever seen if you have really bad back-end that can send anything null 😒, is to prevent nested if-not-null controls, to give a basic example what we're doing to control in Java:

private String getInnerInnerString() {
  if(this.object != null && this.object.innerObject != null
    && this.innerObject.innerInnerString != null) {
    return this.innerObject.innerInnerString;
  }
  return "player_unknown_battleground";
}

With Kotlin 😍

fun getInnerInnerObject():String? {
  return this?.object?.innerObject?.innerInnerString ?: "player_unknown_battleground"
}

So in above example, if any of the references come null until we grab "innerInnerString", Kotlin will return the unknown value directly, and NPE will be prevented, we'll be happy since the app didn't crash. Except these cool stuff, if you're insisting on throwing this error you can simply implement one of following:

val i = h?.length ?: throw NullPointerException()
val i = h!!.length

Versatile

I have dived into too much code on Safe topic, sorry for that 😃 To clear up things back, Let's check Kotlin apart from Java a little bit. What we are observing in past few years is many of new programming languages are being developed in a way to be platform-independent, global, and open-source. For example, one hand, Swift tries to become primary language for iOS app development, on the other hand, it proves that it can be useful for the back-end (ie. IBM's Kitura) So Kotlin varies in four areas on this issues of platform-independence:

  • For server side
  • For Android
  • For JavaScript
  • Kotlin/Native (iOS????)

Using Kotlin for iOS development is also kinda possible. But I don't like to mention it a lot since it's not well proven 👀

Kotlin comes from industry, not academia. It solves problems faced by working programmers today.

I am going to praise Kotlin before concluding the story 😃

You don't have to pay anything or give up from something to start learning it, it's free and open-source! 🆓 💪

When all is said and done it has very neat Java-Kotlin converter. Note: The converter has that qualified to convert one utility class (more than 1000 lines of code) that I'm using in one of the huge projects we have without any errors raised. 😱😱😱

If you have any further interest these are the story links I've used while preparing this one:

Cheers!