DEV Community

Rocky Warren
Rocky Warren

Posted on • Originally published at rocky.dev on

Kotlin: First Impressions

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
Enter fullscreen mode Exit fullscreen mode
  • Immutable variables with type inference
  val b = 2
Enter fullscreen mode Exit fullscreen mode
  • String templates
  val s2 = "${s1.replace("is", "was")}, but now is $a"
Enter fullscreen mode Exit fullscreen mode
  • Type checks and automatic casts
  if (obj is String && obj.length > 0) // obj casted to a string
Enter fullscreen mode Exit fullscreen mode
  • Pattern matching,
  when (obj) {
    1          -> "One"
    "Hello"    -> "Greeting"
    is Long    -> "Long"
    !is String -> "Not a string"
    else       -> "Unknown"
  }
Enter fullscreen mode Exit fullscreen mode
  • Ranges
  for (x in 1..5) ...
Enter fullscreen mode Exit fullscreen mode
  • Immutable collections with lambdas
  val fruits = listOf("banana", "avocado", "apple", "kiwifruit")
  fruits
    .filter { it.startsWith("a") }
    .sortedBy { it }
    .map { it.toUpperCase() }
    .forEach { println(it) }
Enter fullscreen mode Exit fullscreen mode
  • DTOs with equals, copy, toString; can be created without new
  data class Customer(val name: String, val email: String)
Enter fullscreen mode Exit fullscreen mode
  • Default parameter values
  fun foo(a: Int = 0, b: String = "")
Enter fullscreen mode Exit fullscreen mode
  • Extension functions
  fun String.spaceToCamelCase() { ... }
  "Convert this to camelCase".spaceToCamelCase()
  Singletons,
  object Resource {
    val name = "Name"
  }
Enter fullscreen mode Exit fullscreen mode
  • Elvis operator aka "if not null" shorthand
  println(files?.size)
Enter fullscreen mode Exit fullscreen mode
  • "If not null and else" shorthand
  println(files?.size ?: "empty")
Enter fullscreen mode Exit fullscreen mode
  • Get item of possibly empty list
  emails.firstOrNull() ?: ""
Enter fullscreen mode Exit fullscreen mode
  • if expressions
  val result = if (param == 1) "one" else "other"
Enter fullscreen mode Exit fullscreen mode
  • Nullables without the .Get and .HasValue in C#
  val b: Boolean? = ...
  if (b == true) { ... } else { /* b is false or null */ }
Enter fullscreen mode Exit fullscreen mode
  • 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.

Top comments (0)