Kotlin in Action : Chapter 1, What and Why

Caren Chang
2 min readApr 16, 2017

--

The first chapter in the book is an introduction to the language and summarizes the benefits of using Kotlin. If you’re already sold on Kotlin, check out summaries for other chapters:
https://medium.com/@calren24/reading-through-kotlin-in-action-428111b051ce

The first thing to know about Kotlin is that it’s statically typed. This means:

  • type of every expression is known at compile time
  • get compile time errors instead of runtime errors

However, unlike Java, Kotlin doesn’t require variable type to be specified

  • example: val x = 1 (kotlin automatically knows the type is Int, which is also known as type inference)

Benefits of static typing:

  • performance : calling methods is faster
  • reliability : compile time errors instead of runtime crashes-
  • maintainability : easier to see what kind of objects the code is working with

Kotlin also supports functional programming, which means:

  • first-class functions : work with functions as values (store them in variables, pass them in parameters, return them in other functions!)
  • immutability : work with immutable objects

The benefits of functional programming include:

  • conciseness : more power of abstraction lets you avoid code duplication
  • safe multithreading (immutable data structures and pure functions ensure modification of the same data from different threads won’t happen!)
  • easier testing

Kotlin is open source!

Kotlin in android

// kotlin code
view.setOnClickListener {
showToast();
}
// java code
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showToast();
}
});
  • no disadvantage in performance

As demonstrate above, Kotlin was designed to be more concise

  • The majority of the time developers spend is on reading code to understand what’s going on. Concise code can help developers quickly grasp the bigger picture

Kotlin was designed to be a “safe” language:

  • Kotlin’s type system tracks values that can and can’t be null and forbids operations that can lead to NPE at runtime
  • avoids ClassCastException
// kotlin code
if (value is String)
println(value.toUpperCase())
// java code
if (value instance of String) {
println(((String) value).toUpperCase());
}
or worse...
((String) value).toUpperCase()
// causes run time error ClassCastException!

There’s a handy dandy Java-to-Kotlin button converter in Android Studio so you don’t have to write any Kotlin code!

--

--