Skip to content

Instantly share code, notes, and snippets.

@gweakliem
Created August 15, 2019 02:01
Show Gist options
  • Save gweakliem/e10138fa984b949756a4744d501dc600 to your computer and use it in GitHub Desktop.
Save gweakliem/e10138fa984b949756a4744d501dc600 to your computer and use it in GitHub Desktop.
Venkat S. Kotlin for Java Programmers

Kotlin for Java Programmers

  • Multiparadigm language
  • Statically Typed
  • Compiles to java & javascript

"I'll teach you java, let's learn hello world". First word is public. What's public? then static. What's static?.

There's a lot of stuff "you don't need to know right now". Kotlin doesn't make its problems your problems.

fun main() {
  println("Hello world")
}
# compile
kotlinc-jvm hello.kt
# run
kotlin HelloKt
# or run with...
java -classpath . HelloKt

kotlinc-jvm runs a REPL. .kts files are Kotlin script, so you don't even need to declare a function.

Nice things:

  • semicolon is optional - nice for DSLs especially
  • sensible warnings
  • type inference - generally don't declare variable types.
  • val vs var - simple constants
  • string templates & multiline strings
  • positional params & named args, can mix
  • variable sized argument lists
  • destructuring - bind multiple variables in a single statement
  • loop variables are always val, as are function parameters. Constructors are an exception, declaring var makes the property settable
  • Argument matching - using when when is a statement but also an expression in as a clause of when eg in 13..19 -> "teen" isto identify typesis String -> "it's a string"`
  • Java 8 introduced Optional<T>. Problem is you're returning a union object, overhead in memory plus you can always return null for an optional. In Kotlin T? is the nullable version of type T.
  • Elvis operator ?: for handling nullables safely with minimal syntax

Using infix operators you can write DSLs like this, it is a context argument, left, fast, right are receivers.

  operate {
    it turns left
    it runs fast
    it turns right
  }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment