Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Kotlin - Not you grandfather's Java

Kotlin - Not you grandfather's Java

Introduction to Kotlin, for Java developers.

Presented on March 30th 2017 for the Portuguese Java User Group, at Talkdesk's Lisbon Office.

João Carvalho

March 30, 2017
Tweet

More Decks by João Carvalho

Other Decks in Programming

Transcript

  1. public class HelloWorld { public static void main(String... args) {

    System.out .println("Hello world " + args[0]); } }
  2. final String name = "Kotlin"; int age = 5; //

    A few moments later age = 6;
  3. val name: String = "Kotlin" var age: Int = 5

    // A few moments later age = 6
  4. val name = "Kotlin" var age = 5 // A

    few moments later age = 6
  5. fun max(one: Int, other: Int): Int { if (one >

    other) { return one } else { return other } }
  6. fun max(one: Int, other: Int): Int { return if (one

    > other) { one } else { other } }
  7. fun max(one: Int, other: Int): Int = if (one >

    other) { one } else { other }
  8. when (x) { 1 -> print("x == 1") 2 ->

    print("x == 2") else -> { print("x is neither 1 nor 2") } }
  9. fun printStringLength(any: Any) { if (any is String) { println("Length

    is ${any.length}") } else { return println("Oops, not a String") } }
  10. fun printStringLength(any: Any) { val asString = any as String

    println("Length is ${asString.length}") }
  11. fun printStringLength(any: Any) { val asString = any as? String

    println("Length is ${asString?.length ?: "Unknown"}") }
  12. class Fooer(name: String) { init { println("Setting up to foo

    $name") } constructor(name: String, option: String) : this(name) { println("\tUsing option $option") } }
  13. @Override public boolean equals(Object o) { (Stuff generated by your

    IDE) } @Override public int hashCode() { int result = name.hashCode(); result = 31 * result + age; return result; }
  14. emptyList() listOf(1, 2, 3) mutableListOf(1, 2, 3) emptySet() setOf("John", "Jane")

    mutableSetOf("John", "Jane") emptyMap() mapOf("John" to "Doe") mutableMapOf("John" to "Doe")
  15. // apply BaseClientDetails().apply { clientId = "foo" } // takeIf

    userRepository.findOne("foo")?.takeIf(User::active) // use inputStream.use { it.read() } // let clientId?.let { loadClient(it) }
  16. fun <T> doWithinLock(lock: Lock, body: () -> T): T {

    lock.lock() try { return body() } finally { lock.unlock() } }
  17. class HTML { var value = "" fun body(value: String)

    { this.value = value } } fun html(init: HTML.() -> Unit) = HTML().apply { init() } html { body("Hello world") }