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

Introduction to Kotlin

Sponsored · Ship Features Fearlessly Turn features on and off without deploys. Used by thousands of Ruby developers. →
Avatar for Patrick Yin Patrick Yin
September 15, 2017

Introduction to Kotlin

Introduction to Kotlin language

Avatar for Patrick Yin

Patrick Yin

September 15, 2017

Other Decks in Programming

Transcript

  1. INTRODUCTION WHAT IS KOTLIN? ▸ It is a Russian Island:

    Котлин. In English, the name is usually pronounced “cot- lin,” not “coat-lin” or “caught-lin.” ▸ It is a statically typed programming language that runs on the JVM ▸ Created by JetBrains, first release - July 2011, latest release v1.1.4-3 - Aug 2017 ▸ It can be used for developing server-side, Android applications, and also provides the ability to target JavaScript
  2. INTRODUCTION WHY WE USE IT? ▸ Great IDEs supporting such

    as Android Studio, IntelliJ IDEA ▸ Higher functions and lambda’s ▸ Class extensions ▸ Strongly typed with inferred data types and say goodbye to NullPointException ▸ Write more with much less code ▸ Generates very similar bytecode to Java ▸ 100% interoperable with Java and Android ▸ Now official on Android
  3. IN ACONEX MOBILE TEAM, WE WORK WITH KOTLIN LANGUAGE EVERYDAY,

    USE 100% KOTLIN CODE IN OUR NEW ANDROID APP.
  4. PRACTICE INFERRED TYPE, NULLABLE TYPES AND LATE INIT val l

    = 1L + 3 // With type inferencing, Long + Int => Long
 val str: String = “string" // Without type inferencing // Non-Null type
 var a: String = "abc"
 a = null // compilation error
 
 // Nullable type
 var b: String? = "abc"
 b = null // ok
 val l = b.length // error: variable 'b' can be null
 
 // Safe Calls
 b?.length lateinit var presenter: DashboardPresenter
  5. PRACTICE INTERFACES interface MyInterface {
 val prop: Int // abstract


    
 val propertyWithImplementation: String
 get() = "foo"
 
 fun foo() {
 print(prop)
 }
 }
 
 class Child : MyInterface {
 override val prop: Int = 29
 }
  6. PRACTICE EXTENSION FUNCTIONS fun <T> MutableList<T>.swap(index1: Int, index2: Int) {


    val tmp = this[index1]
 this[index1] = this[index2]
 this[index2] = tmp
 } val l = mutableListOf(1, 2, 3)
 l.swap(0, 2) // 'this' inside 'swap()' will hold the value of 'l'
  7. PRACTICE DATA CLASS data class Forecast(
 @SerializedName("date") val date: Date,


    @SerializedName("temp") val temperature: Float,
 @SerializedName("desc") val description: String) // that’s all the declaration
 
 val f1 = Forecast(Date(), 27.5f, "Storming")
 val f2 = f1.copy(temperature = 31f) // Destructuring Declarations
 val jane = User("Jane", 35)
 val (name, age) = jane
 println("$name, $age years of age") // prints "Jane, 35 years of age”
  8. PRACTICE CONTROL FLOW when {
 x.isOdd() -> print("odd")
 x.isEven() ->

    print("even")
 else -> print("x is weird")
 } when (x) {
 0, 1 -> print("x == 0 or x == 1")
 else -> print("otherwise")
 } when (x) {
 parseInt(s) -> print("s encodes x")
 else -> print("s does not encode x")
 } when (x) {
 in 1..10 -> print("x is in the range")
 !in 10..20 -> print("outside the range")
 else -> print("none of the above")
 }
  9. PRACTICE `WITH` AND `APPLY` FUNCTIONS fun alphabet(): String {
 val

    result = StringBuilder()
 for (letter in 'A'..'Z') {
 result.append(letter)
 }
 result.append("\nNow I know the alphabet!")
 return result.toString()
 } fun alphabet() = with(StringBuilder()) {
 for (letter in 'A'..'Z') {
 append(letter)
 }
 append("\nNow I know the alphabet!")
 toString() }
 fun alphabet() = StringBuilder().apply {
 for (letter in 'A'..'Z') {
 append(letter)
 }
 append("\nNow I know the alphabet!")
 }.toString()
  10. PRACTICE FUNCTIONAL OPERATIONS strings.filter { it.length == 5 }
 .sortedBy

    { it }
 .map { it.toUpperCase() } 
 var sum = 0
 ints.filter { it > 0 }
 .forEach { sum += it }
 print(sum)
 
 val list = listOf(1, 2, 3, 4, 5, 6)
 list.any { it % 2 == 0 }
 list.all { it < 10 }
 list.count { it % 2 == 0 }
 list.forEachIndexed { index, value -> println("position $index contains a $value") }
  11. KOTLIN 1.1 JAVASCRIPT ▸ JavaScript target is no longer experimental

    ▸ ECMAScript 5.1, plans to target ECMAScript2015 ▸ JS libs available through typed APIs
  12. KOTLIN 1.1 TYPE ALIAS typealias FileTable<K> = MutableMap<K, MutableList<File>> 


    fun countFiles(fileTable: FileTable<Int>) = fileTable.count()
  13. KOTLIN 1.1 DESTRUCTURING IN LAMBDAS val map = mapOf(1 to

    "one", 2 to “two") 
 // before
 println(map.mapValues { entry ->
 val (key, value) = entry
 "$key -> $value!"
 }) 
 // now
 println(map.mapValues { (key, value) -> "$key -> $value!" })
  14. KOTLIN 1.1 OTHERS ▸ Underscores for unused parameters
 val (_,

    status) = getResult()
 ▸ Shorter syntax for properties
 data class Person(val name: String, val age: Int) {
 val isAdult get() = age >= 20 // Property type inferred to be 'Boolean'
 }
  15. KOTLIN 1.1 MORE NEWS AGAIN ▸ Java 8 bytecode support

    ▸ Java 8 standard library support ▸ Constant inlining (const val) ▸ Gradle incremental compilation is now enabled by default
  16. INCONVENIENCES AUTO COMPLETION (RxJava) The IDE knows the return type

    of the map function when we use Java, but when using Kotlin, it doesn’t. I need some hint…
  17. INCONVENIENCES RxKotlin ▸ The `TestRule` in `RxJavaPlugins` couldn't be applied

    to RxKotlin's methods, so only using RxJava in Kotlin project at the moment.