Skip to content

Instantly share code, notes, and snippets.

@tfga
Created September 14, 2019 23:22
Show Gist options
  • Save tfga/9900912b577469c28104c35c296af9a6 to your computer and use it in GitHub Desktop.
Save tfga/9900912b577469c28104c35c296af9a6 to your computer and use it in GitHub Desktop.

Why you should switch to Kotlin

  1. Low cost of transition

    • You can continue using Maven (unlike in Scala, where Maven support is really bad and you eventually have to switch to sbt)

    • Kotlin and Java files can co-exist in the same project.

    • In IntelliJ, when you paste Java code into a Kotlin file, the IDE converts the code for you on the fly. (The conversion is not perfect. But, still).

  2. No more NPEs

    NullPointerExceptions are caught at compile-time. Code that would result in a NPE at run-time in Java, in Kotlin doesn't compile. That alone should be reason enought to migrate.

    The type system is "null-aware" and knows when you're using a variable that might be null. (It's flow-sensitive. Which also allows for other clever things such as smart casts).

  3. Variable interpolation

  4. Better lambdas

    In Java (and JS), there are have several syntactic forms for lambdas:

    x -> x * x                      // single arg, expression
    (x, y) -> x + y                 // multiple args, expression
    x -> { print(x); }              // single arg, block
    (x, y) -> { print(x, y); }      // multiple args, block

    Kotlin, on the other hand, follows the Highlander Principle ("There can be only one!"):

    { x -> x * x          }       // single arg, expression
    { x, y -> x + y       }       // multiple args, expression
    { x -> print(x)       }       // single arg, block
    { x, y -> print(x, y) }       // multiple args, block

    See also: autovar.

  5. Function types

    If an argument is a function of the type () -> String, that's what you put in the type signature:

    fun f(getString: () -> String) {
    
        println(getString())
    }

    You don't need to know that this corresponds to Supplier<String> -- nor about any of the other dozens of fancy-named "functional interfaces" in the standard library.

  6. More

    Type inference, multi-line strings, default and named parameters...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment