Chapter 49. Kotlin Is a Thing

Mike Dunn

Java is maybe the most mature and vetted language still in common use, and that is unlikely to change dramatically in the foreseeable future. To facilitate modern notions of what a programming language should do, some smart folks decided to write a new language that did all the Java Things, plus some cool new Things that would be fairly painless to learn and be largely interoperable. Someone like me, who’s been working on the same huge Android app for years, can decide to write a single class in Kotlin without committing to a complete migration.

Kotlin is meant to let you write shorter, cleaner, more modern code. While modern and preview versions of Java do address a lot of the issues Kotlin manages, Kotlin can be especially useful for Android developers, who are stuck somewhere between Java 7 and Java 8.

Let’s look at a few examples, like Kotlin’s property constructor pattern for models, starting with a simple example of what a Java model may look like:

public class Person {
  private String name;
  private Integer age;
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public Integer getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }
}

We could create a special constructor to take some initial values:

public class Person {
  public Person(String name, Integer age) {
    this.name = name;
    this.age = age;
  }
  ...
}

Not too bad, but you can probably see how a few more properties could make the definition for this pretty simple class get bloated really quickly. Let’s take a look at that class in Kotlin:

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

That’s it! Another neat example is delegation. Kotlin delegates allow you to provide logic for any number of read operations. One example is the lazy initialization, a concept sure to be familiar to Java developers. It might look like this:

public class SomeClass {
  private SomeHeavyInstance someHeavyInstance = null;
  public SomeHeavyInstance getSomeHeavyInstance() {
    if (someHeavyInstance == null) {
      someHeavyInstance = new SomeHeavyInstance();
    }
    return someHeavyInstance;
  }
}

Again, not too terrible, done simply and without configuration, but chances are you’ll repeat this same code several times in your code, violating the DRY principle (Don’t Repeat Yourself). Also, not thread-safe. Here’s the Kotlin version:

val someHeavyInstance by lazy {
  return SomeHeavyInstance()
}

Short and sweet and readable. All that boilerplate is tucked away nicely under the covers. Oh, and it’s thread-safe too. null safety is also a big upgrade. You’ll see a lot of question mark operators following a nullable reference in Kotlin:

val something = someObject?.someMember?.anotherMember

Here’s the same thing in Java:

Object something = null;
if (someObject != null) {
  if (someObject.someMember != null) {
    if (someObject.someMember.anotherMember != null) {
      something = someObject.someMember.anotherMember;
    }
  }
}

The null-check operator (?) will stop evaluating immediately and return null as soon as any of the referents in the chain resolve to null.

Let’s close out with another killer feature: coroutines. In a nutshell, a coroutine performs work asynchronous to the calling code, although that work may be handed off to some number of threads. It’s important to note that even if a single thread handles multiple coroutines, Kotlin performs some context-switching magic that runs multiple jobs concurrently. While specific behavior is configurable, coroutines naturally use a dedicated thread pool, but use context switching within a single thread (so hot). Since they’re Kotlin, they also can be fancy and sophisticated and overengineered, but by default they’re also super simple:

launch {
  println("Hi from another context")
}

Be aware of the differences between threads and coroutines though—for example, an object.wait() invocation in one job will pause all the other jobs working in the containing thread. Give Kotlin a spin and see what you think.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.32.86