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

Kotlin for Android 101

Kotlin for Android 101

By Brice

Buzzvil

May 09, 2018
Tweet

More Decks by Buzzvil

Other Decks in Programming

Transcript

  1. /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
  2. /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
  3. /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
  4. /39 References • Home Page • Source code • Kotlin

    Koans – tutorial • Official References • 깡샘의 코틀린 프로그래밍 7
  5. /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
  6. /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
  7. /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
  8. /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
  9. /39 Normal File / Class File • Normal File: not

    a class-only file • Class File: a class-only file 13
  10. /39 Variable val value: Int val value2 = 1 var

    value3: String var value4 = "test" var value5: Boolean = false var value6: Boolean? = null 14
  11. /39 Val / Var • Value (val): assign-once variable •

    Variable (var): mutable variable 15
  12. /39 Types • Numbers • Characters • Booleans • Arrays

    • Strings • Any • Unit • Nothing 16
  13. /39 Numbers • Types • Double • Float • Long

    • Int • Short • Byte • Char • Literals • 123 • 1_000_000 • 123L • 0x0F • 0xFF_AB_CD • 0b001 17
  14. /39 Arrays • class Array<T> private constructor() { val size:

    Int operator fun get(index: Int): T operator fun set(index: Int, value: T): Unit operator fun iterator(): Iterator<T> // ... } • val x: IntArray = intArrayOf(1, 2, 3) 20
  15. /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
  16. /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
  17. /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
  18. /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
  19. /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
  20. /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
  21. /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
  22. /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
  23. /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
  24. /39 Functions • fun read(b: Array<Byte>, off: Int = 0,

    len: Int = b.size): Int { ... } • read(byteArrayOf(1, 2, 3).toTypedArray(), off = 0) 32
  25. /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
  26. /39 Equality • Structural Equality • a == b •

    a?.equals(b) ?: (b === null) • Referential Equality • a === b 34
  27. /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
  28. /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
  29. /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<TextView>(R.id.textView) textView.setText("Hello, world!") } } 37