Kotlin: First Impressions

Rocky Warren
Rocky Warren
March 3, 20202 min read

I played around with Kotlin recently and was pretty impressed. It seems like they took the best parts of C#, Scala, and Go. Here's a quick rundown of some features.

  • Expression bodied functions

    fun sum(a: Int, b: Int) = a + b
    
  • Immutable variables with type inference

    val b = 2
    
  • String templates

    val s2 = "${s1.replace("is", "was")}, but now is $a"
    
  • Type checks and automatic casts

    if (obj is String && obj.length > 0) // obj casted to a string
    
  • Pattern matching,

    when (obj) {
      1          -> "One"
      "Hello"    -> "Greeting"
      is Long    -> "Long"
      !is String -> "Not a string"
      else       -> "Unknown"
    }
    
  • Ranges

    for (x in 1..5) ...
    
  • Immutable collections with lambdas

    val fruits = listOf("banana", "avocado", "apple", "kiwifruit")
    fruits
      .filter { it.startsWith("a") }
      .sortedBy { it }
      .map { it.toUpperCase() }
      .forEach { println(it) }
    
  • DTOs with equals, copy, toString; can be created without new

    data class Customer(val name: String, val email: String)
    
  • Default parameter values

    fun foo(a: Int = 0, b: String = "")
    
  • Extension functions

    fun String.spaceToCamelCase() { ... }
    "Convert this to camelCase".spaceToCamelCase()
    Singletons,
    object Resource {
      val name = "Name"
    }
    
  • Elvis operator aka "if not null" shorthand

    println(files?.size)
    
  • "If not null and else" shorthand

    println(files?.size ?: "empty")
    
  • Get item of possibly empty list

    emails.firstOrNull() ?: ""
    
  • if expressions

    val result = if (param == 1) "one" else "other"
    
  • Nullables without the .Get and .HasValue in C#

    val b: Boolean? = ...
    if (b == true) { ... } else { /* b is false or null */ }
    
  • The main Go influence seems to be coroutines (lightweight threads) for async code. They also reminded me of C#'s async/await, here's a good explanation.

Share or comment on Twitter