Slide 1

Slide 1 text

/39 Kotlin for Android 101 2018.05.09 Brice Buzzvil 1

Slide 2

Slide 2 text

/39 Wait, wait, wait. Brice, YOUR QUIZ!! You ruined my weekends! 2

Slide 3

Slide 3 text

/39 Quiz • In an array, the most of the numbers are twice, but two different numbers are only once. ex) {1, 5, 6, 6, 1, 2} Find the algorithm that can find the two numbers which has time complexity O(n) and space complexity O(1). No sort No radix sort Not sorted XOR 3

Slide 4

Slide 4 text

/39 Solution {1, 5, 6, 6, 1, 2} 1. XOR all the numbers = 1^5^6^6^1^2 = 2^5 = 010^101 = 111 2. Choose any bit which is 1 • Iterate all the bits or try this: The smallest 1 = x & -x 3. Find all the numbers the bit is 0, and XOR to find one answer • G0 = {6, 6, 2}, XOR(G0) = 6^6^2 = 2 4. Find all the numbers the bit is 1, and XOR to find the other answer • G1 = {1, 5, 1}, XOR(G1) = 1^5^1 = 5 4

Slide 5

Slide 5 text

/39 Solution (python3 code except lambda keyword) from functools import reduce def solution(array): xor = reduce(x, y: x ^ y, array, 0) bit = xor & -xor a = reduce(x, y: x ^ y, filter(x: not x & bit, array), 0) b = reduce(x, y: x ^ y, filter(x: x & bit, array), 0) return a, b print(solution([1, 5, 6, 6, 1, 2])) # (2, 5) 5

Slide 6

Slide 6 text

/39 Kotlin for Android 101 2018.05.09 Brice Buzzvil 6

Slide 7

Slide 7 text

/39 References • Home Page • Source code • Kotlin Koans – tutorial • Official References • 깡샘의 코틀린 프로그래밍 7

Slide 8

Slide 8 text

/39 The Billion Dollar Mistake I call it my billion-dollar mistake. It was the invention of the null reference in 1965. At that time, I was designing the first comprehensive type system for references in an object oriented language (ALGOL W). My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn't resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years. - Tony Hoare, 2009 Kotlin's type system is aimed at eliminating the danger of null references from code, also known as the The Billion Dollar Mistake. 8

Slide 9

Slide 9 text

/39 • Statically typed programming language • Can be compiled to • Java virtual machine bytecode • JavaScript source code • Designed by JetBrains • First appeared in 2011 • Fully supported by Google on the Android OS (Android Studio 3.0) 9

Slide 10

Slide 10 text

/39 Hello, world! package hello fun main(args: Array) { println("Hello World!") } 10

Slide 11

Slide 11 text

/39 Characteristics • *.kt • Decoupling file and class • Decoupling package and file location • No semicolon (;) at the end of lines • No ‘static’ keyword • Null-aware types • Functional programming • Simplified and modern features added version of Java 11

Slide 12

Slide 12 text

/39 Kotlin for Android • Compatibility: Fully compatible with JDK 6 • Performance: Runs as fast as equivalent java one • Interoperability: 100% interoperable with Java • Footprint: Compact runtime library (proguarded, <=100KB) • Compilation Time: Supports efficient incremental compilation • Learning Curve: Automated Java to Kotlin converter, guides • http://kotlinlang.org/docs/reference/android-overview.html 12

Slide 13

Slide 13 text

/39 Normal File / Class File • Normal File: not a class-only file • Class File: a class-only file 13

Slide 14

Slide 14 text

/39 Variable val value: Int val value2 = 1 var value3: String var value4 = "test" var value5: Boolean = false var value6: Boolean? = null 14

Slide 15

Slide 15 text

/39 Val / Var • Value (val): assign-once variable • Variable (var): mutable variable 15

Slide 16

Slide 16 text

/39 Types • Numbers • Characters • Booleans • Arrays • Strings • Any • Unit • Nothing 16

Slide 17

Slide 17 text

/39 Numbers • Types • Double • Float • Long • Int • Short • Byte • Char • Literals • 123 • 1_000_000 • 123L • 0x0F • 0xFF_AB_CD • 0b001 17

Slide 18

Slide 18 text

/39 Characters • Characters are not a number 18

Slide 19

Slide 19 text

/39 Booleans • true / false • ||, &&, ! 19

Slide 20

Slide 20 text

/39 Arrays • class Array private constructor() { val size: Int operator fun get(index: Int): T operator fun set(index: Int, value: T): Unit operator fun iterator(): Iterator // ... } • val x: IntArray = intArrayOf(1, 2, 3) 20

Slide 21

Slide 21 text

/39 Strings • for (c in str) { println(c) } • val text = """ |Tell me and I forget. |Teach me and I remember. |Involve me and I learn. |(Benjamin Franklin) """.trimMargin() • val s = "abc" println("$s.length is ${s.length}") // prints "abc.length is 3" 21

Slide 22

Slide 22 text

/39 Any, Unit, Nothing • Any • The topmost class of Kotlin • Unit • There is no return value (similar to void, but a type) • val unit: Unit = kotlin.Unit • Nothing • There is no return value / Never returns • fun myFun(): Nothing { while (true) {...} } fun myFun2(): Nothing { throw Exception() } 22

Slide 23

Slide 23 text

/39 ? • type: @NotNull • type?: @Nullable 23

Slide 24

Slide 24 text

/39 Control Flow • If • when • for • while 24

Slide 25

Slide 25 text

/39 If • If is an expression à it returns a value • val result = if (a > b) a else b • val max = if (a > b) { print("Choose a") a } else { print("Choose b") b } 25

Slide 26

Slide 26 text

/39 When • Improved switch operator • var x: Any when (x) { 0 -> print("x == 0") 1, 2 -> print("x == 1 or x == 2") parseInt(s) -> print("x == s") is String -> print("x length: ${x.length}") // Smart cast else -> print("otherwise") } • when { x.isOdd() -> print("x is odd") x.isEven() -> print("x is even") else -> print("x is funny") } 26

Slide 27

Slide 27 text

/39 For • for (i in 1..3) print(i) for ((i, v) in (1..3).withIndex()) { print(i) print(v) } for (i in 6 downTo 0 step 2) { print(i) } 27

Slide 28

Slide 28 text

/39 Class • open class Demo constructor(name: String) { val firstProperty = "First property: $name".also(::println) init { println("First initializer block that prints ${name}") } val secondProperty = "Second property: ${name.length}".also(::println) init { println("Second initializer block that prints ${name.length}") } constructor(name: String, age: Int): this(name) { } } val demo = Demo("brice") 28

Slide 29

Slide 29 text

/39 Properties and Fields • class Demo constructor() { var name: String = "" } • class Demo constructor() { var name: String = "" get() = field set(value) { field = value } } • BuzzScreen.getInstance().getUserProfile().setUserId("testId"); • BuzzScreen.getInstance().userProfile.userId = "testId" 29

Slide 30

Slide 30 text

/39 Data Type Object (DTO, POJO, POCO) • data class Customer(val name: String, val email: String) • getters and setters for all properties • name = c.name vs name = c.getName() • c.name = “name” vs c.setName(“name”) • equals() • hashCode() • toString() • copy() • component1(), … for all properties 30

Slide 31

Slide 31 text

/39 Destructuring Declarations • data class Customer(val name: String, val email: String) • val (name, email) = Customer("name", "[email protected]") • val name = customer.component1() val email = customer.component2() 31

Slide 32

Slide 32 text

/39 Functions • fun read(b: Array, off: Int = 0, len: Int = b.size): Int { ... } • read(byteArrayOf(1, 2, 3).toTypedArray(), off = 0) 32

Slide 33

Slide 33 text

/39 High Order Functions and Lambdas • High Order Function: A function that takes functions as params or return functions • Lambda Expression • max(strings, { a, b -> a.length < b.length }) • LINQ Style Code • students.filter { it.avgGrade > 4.0 } .sortedBy { it.avgGrade } .take(10) .sortedWith(compareBy( { it.surname }, { it.name })) • Anonymous Function • fun(x: Int, y: Int): Int = x + y • Closures • var sum = 0 ints.filter { it > 0 }.forEach { sum += it } print(sum) 33

Slide 34

Slide 34 text

/39 Equality • Structural Equality • a == b • a?.equals(b) ?: (b === null) • Referential Equality • a === b 34

Slide 35

Slide 35 text

/39 Calling Java code from Kotlin • getter and setter / isBoolean : access it as property • fun calendarDemo() { val calendar = Calendar.getInstance() if (calendar.firstDayOfWeek == Calendar.SUNDAY) { // call getFirstDayOfWeek() calendar.firstDayOfWeek = Calendar.MONDAY // call setFirstDayOfWeek() } if (!calendar.isLenient) { // call isLenient() calendar.isLenient = true // call setLenient() } } • https://kotlinlang.org/docs/reference/java-interop.html 35

Slide 36

Slide 36 text

/39 Calling Kotlin code from Java • Properties -> getter / setter • Package Level Functions • https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html // example.kt package demo class Foo fun bar() { } new demo.Foo(); demo.ExampleKt.bar(); 36

Slide 37

Slide 37 text

/39 Tools – Kotlin Android Extensions • // Using R.layout.activity_main from the 'main' source set import kotlinx.android.synthetic.main.activity_main.* class MyActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Instead of findViewById(R.id.textView) textView.setText("Hello, world!") } } 37

Slide 38

Slide 38 text

/39 Apps built with Kotlin 38

Slide 39

Slide 39 text

/39 Kotlin Koans https://try.kotlinlang.org/ 39

Slide 40

Slide 40 text

/39 Questions 40