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

Intro to Kotlin

Sponsored · Your Podcast. Everywhere. Effortlessly. Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.
Avatar for Dan Rusu Dan Rusu
September 13, 2018

Intro to Kotlin

Introduction to the Kotlin programming language as presented at:
https://www.meetup.com/Kotlin-Waterloo-P2P/

Avatar for Dan Rusu

Dan Rusu

September 13, 2018
Tweet

More Decks by Dan Rusu

Other Decks in Programming

Transcript

  1. FR Meetup Goals • Administrated by Veronika Keir • Frequency

    • Format • Speakers • Engagement 2
  2. FR Hello World Kotlin • No class (fix static) •

    Declaration order (cognitive load) • Inferred variable types (but still statically typed) • Semicolons • println wrapper • String Templates Java Spot the bug? 3 fun main(args: Array<String>) { val name = "Dan" val salary = 3 println("$name makes $salary million dollars") } public class HelloWorld { public static void main(String[] args) { final String name = "Dan"; final int salary = 3; System.out.println(name + "makes" + salary + "million dollars"); } }
  3. What is Kotlin • Statically typed programming language developed by

    JetBrains • Started in 2010. Official 1.0 release in Feb. 2016 • Free & open source • Pragmatic. Increases productivity and prevents common defects • Interoperable with Java • Official Google support • Exponential growth 4
  4. FR Motivation • Easy to learn • Automatic Java to

    Kotlin conversion • Increased robustness • Entire classes of Java defects are prevented • Increased productivity • 40% line-count reduction vs Java • Fewer bugs to fix • Increased re-usability • Code is more obvious • Career Growth 5
  5. FR Null Safety • Safe call operator “?.” returns null

    if the variable is null • Elvis operator “?:” returns the right expression when the left is null • Forced to decide how null is handled at compile time • Roughly 30% of all defects are caused by incorrect null assumptions 6 var name: String = "Dan" name = null // Compiler error, name is not nullable // Nullable types are declared with “?” var spouseName: String? = getSpouseName() // null if not married name = spouseName // Compiler error, spouseName might be null var spouseValue: Int = spouseName.length // Compiler error, spouseName might be null if (spouseName != null) spouseValue = spouseName.length // allowed spouseValue = spouseName?.length ?: 0 // Default to 0 if spouseName is null
  6. FR Data Classes Kotlin • A simple data class is

    horrendous in Java! • Not a fair comparison (for Kotlin!) 7 public class Person { private final int id; @Nonnull private String name; public Person(int id, @Nonnull final String name) { this.id = id; this.name = name; } @Override public String toString() { return "Person{id = " + id + ", name = " + name + '}'; } public int getId() { return id; } @Nonnull public String getName() { return name; } public void setName(@Nonnull final String name) { this.name = name; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Person person = (Person) o; return id == person.id && name.equals(person.name); } @Override public int hashCode() { return 31 * id + name.hashCode(); } } data class Person(val id: Int, var name: String)
  7. Data Classes Avoid Defects • Missing Override annotation and incorrect

    method signature • e.g. incorrect equals method parameter type, hashcode instead of hashCode, etc. • Incorrect or inconsistent equals & hashCode implementation • Missing nullability annotations or forgetting to guard against null parameters • Modifications are made and equals / hashCode / toString / copy are forgotten or updated incorrectly • +more 8
  8. FR Lambdas / Higher Order Functions 9 val myLock =

    ReentrantLock() inline fun lock(lock: Lock, body: () -> Unit) { lock.lock() try { body() } finally { lock.unlock() } } fun stealMoney() { lock (myLock) { val victim = loadPerson(“Kyle Platt") val thief = loadPerson(“Dan Rusu") transferBalance(from = victim, to = thief) } }
  9. Higher Order Function Benefits • Can define new language constructs!

    • Additional patterns can now be extracted • Significant reduction of repetitive code • Only need to test & fix in 1 location • Can create DSLs (Domain Specific Language) • Inlined lambdas avoid scalability issues • Also makes debugging easier 10
  10. FR Extension Functions 11 fun String?.size(): Int = this?.length ?:

    0 fun JavaPerson.isEven(): Boolean = age % 2 == 0 fun main(args: Array<String>) { val person: JavaPerson = JavaPersonFactory.loadPerson(123) val name = person.name when { person.isEven() -> println("$name should be promoted") person.age > 100 -> println("""$name is “voluntarily” retiring""") else -> println(“$name isn’t interesting") } }
  11. FR Extension Function Benefits • Discoverability • Discovering existing utility

    functions • Re-inventing the wheel across teams • Null handling • Forgetting to tackle the null case or excessive null-check clutter • Improved readability • E.g. name.isNullOrEmpty() instead of MyStringUtils.isNullOrEmpty(name) • Promotes loose coupling • Add capabilities only where needed 12
  12. FR Logging Example 13 object FileAppender { // Singleton pattern

    built into the language fun appendLine(fileName: String, message: String) { ... } } class Logger(val context: Class<Any>) { inline fun debug(message: () -> String) { if (debugEnabled) { // only evaluate the message if logging is enabled FileAppender.appendLine("server.log", "DEBUG: ${ message() }") } } } // Optional parameter! No more overloading hell (especially JavaDocs replication) class BankAccount(val id: Long, private var balance: BigDecimal = 100.toBigDecimal()) { private val logger by lazy { Logger(javaClass) } // efficient thread-safe lazy initialization!!! fun withdrawFunds(amount: BigDecimal) { logger.debug { "Withdrawing $amount dollars from $id" } balance -= amount // Wow! BigDecimal is actually nice to use in Kotlin } }
  13. Misconceptions • Memory usage • Inlined lambdas reduce memory consumption

    • Security / Security Expertise • Using the same Java utilities • Same Java security practices apply • Tooling • IDE / static analysis / Crucible / TeamCity / Junit / etc. support • Ramp-up • Auto converter & built-in decompile to Java • Edu Tools (Free IntelliJ plugin with Kotlin Koans course) 15