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

Kotlin for Android: Starting out with confidence

Kotlin for Android: Starting out with confidence

An Introduction to Kotlin for Android Developers presented at GDG Uyo IO Extended Conference

Avatar for Ememobong Akpanekpo

Ememobong Akpanekpo

May 24, 2018

Other Decks in Programming

Transcript

  1. var temperature : Int = 1 // has type Int

    val numberMembers = 5 //automatically inferred type Int val percentage = 80 / 100 percentage = 30 //does not compile var percentage = 80 / 100 percentage = 30 //compiles
  2. var temperature : Int = 1 // has type Int

    val numberMembers = 5 //automatically inferred type Int val percentage = 80 / 100 percentage = 30 //does not compile var percentage = 80 / 100 percentage = 30 //compiles
  3. var temperature : Int = 1 // has type Int

    val numberMembers = 5 //automatically inferred type Int val percentage = 80 / 100 percentage = 30 //does not compile var percentage = 80 / 100 percentage = 30 //compiles
  4. var temperature : Int = 1 // has type Int

    val numberMembers = 5 //automatically inferred type Int val percentage = 80 / 100 percentage = 30 //does not compile var percentage = 80 / 100 percentage = 30 //compiles
  5. //No Nulls Allowed var average : Double = 1.0 average

    = 2.0 average = null //Allows nulls var average : Double? = 1.0 average = 2.0 average = null
  6. // Double !! -> NullPointerException val l = name!!.length //

    Safe Call ?. with chains val name = bob?.department?.head?.name // Elvis Operator val length = b?.length ?: -1
  7. // Double Bang !! -> NullPointerException val l = b!!.length

    // Safe Call ?. with chains val name = bob?.department?.head?.name // Elvis Operator val length = b?.length ?: -1
  8. // Double Bang !! -> NullPointerException val l = b!!.length

    // Safe Call ?. with chains val name = bob?.department?.head?.name // Elvis Operator ?: val length = b?.length ?: -1
  9. val name : String? = "hello" name?.let { //Now name

    is not null at this point textView.text = name } // There are whole bunch more - .with{} .run{} - with slight diferences // Can also just do a normal null check!
  10. class EventsActivity : AppCompatActivity() { private lateinit var recyclerViewAdapter: SimpleAdapter

    override fun onCreate(savedInstanceState: Bundle?) { // Other initialization stuf recyclerViewAdapter = SimpleAdapter(/*..*/) } }
  11. val lazyValue: String by lazy { println("computed!") "Hello" } fun

    main(args: Array<String>) { println(lazyValue) println(lazyValue) } computed! Hello Hello
  12. when (s) { 1 -> print("x == 1") 2 ->

    print("x == 2") else -> { // Note the block print("x is neither 1 nor 2") } }
  13. enum class Currency { GBP, ZAR; } when (currency) {

    Currency.GBP -> doSomething() Currency.ZAR -> doAnotherThing() }
  14. enum class Currency { GBP, USD, ZAR; } when (currency)

    { Currency.GBP -> doSomething() Currency.ZAR -> doAnotherThing() }
  15. enum class Currency { GBP, USD, ZAR; } when (currency)

    { Currency.GBP -> doSomething() Currency.ZAR -> doAnotherThing() else -> doNothing() }
  16. fun calculateSum(a: Int, b: Int) : Int { return a

    + b } fun calculateSum(a: Int, b: Int) = a + b
  17. fun calculateSum(a: Int, b: Int) : Int { return a

    + b } fun calculateSum(a: Int, b: Int) = a + b
  18. fun String.hello(): String = "Hello " + this // use

    the new hello() method val hi = "Kotlin !".hello() Hello Kotlin ! fun TextView.getFloatValue() : Float { return 0f } val foat = textViewHello.getFloatValue()
  19. fun String.hello(): String = "Hello " + this // use

    the new hello() method val hi = "Kotlin !".hello() Hello Kotlin ! fun TextView.getFloatValue() : Float { return 0f } val num = textViewHello.getFloatValue()
  20. fun calculateSum(a: Int = 2, b: Int) : Int {

    return a + b } val sum = calculateSum(b = 3) 5 //Can be done on Constructors as well as functions
  21. val exampleArray = arrayListOf(3,324,5,6,3,2,6,8,1,2,4,3,2) exampleArray.flter { it % 2 ==

    0 } [324, 6, 2, 6, 8, 2, 4, 2] val numberList = arrayListOf(1,2,3,4,5,6,7,8,9) numberList.map { it * 2 } .flter { it % 3 == 0} [6, 12, 18]
  22. val exampleArray = arrayListOf(3,324,5,6,3,2,6,8,1,2,4,3,2) exampleArray.flter { it % 2 ==

    0 } [324, 6, 2, 6, 8, 2, 4, 2] val numberList = arrayListOf(1,2,3,4,5,6,7,8,9) numberList.map { it * 2 } .flter { it % 3 == 0} [6, 12, 18]
  23. fun calcPercentage(value: Int, onComplete: (output : Double) -> Unit) {

    val calculation = value / 100.0 onComplete(calculation) } //called in onCreate or wherever calculatePercentage(2) { Log.d("MainActivity", "Calculation Complete: $it") } Calculation Complete: 0.02
  24. fun calcPercentage(value: Int, onComplete: (input : Double) -> Unit) {

    val calculation = value / 100.0 onComplete(calculation) } //called in onCreate or wherever calcPercentage(2) { Log.d("MainActivity", "Calculation Complete: $it") } Calculation Complete: 0.02
  25. fun <T> executeWork(job: () -> T) : T { Log.d(TAG,

    "Work started") val result = job() Log.d(TAG, "Work Fin") return result } val number = executeWork { 100 * 5 } Log.d(TAG, "Result: $number") val stringCalc = executeWork { "Rebecca".plus(" Hello") } Log.d(TAG, "String: $stringCalc") Work started Work Fin Result: 500 Work started Work Fin String: Rebecca Hello
  26. fun <T> executeWork(job: () -> T) : T { Log.d(TAG,

    "Work started") val result = job() Log.d(TAG, "Work Fin") return result } val number = executeWork { 100 * 5 } Log.d(TAG, "Result: $number") val stringCalc = executeWork { "Rebecca".plus(" Hello") } Log.d(TAG, "String: $stringCalc") Work started Work Fin Result: 500 Work started Work Fin String: Rebecca Hello
  27. fun <T> executeWork(job: () -> T) : T { Log.d(TAG,

    "Work started") val result = job() Log.d(TAG, "Work Fin") return result } val number = executeWork { 100 * 5 } Log.d(TAG, "Result: $number") val stringCalc = executeWork { "Rebecca".plus(" Hello") } Log.d(TAG, "String: $stringCalc") Work started Work Fin Result: 500 Work started Work Fin String: Rebecca Hello
  28. class Admin : User { val name: String val age:

    Int constructor(name : String, age : Int){ this.name =name this.age = age } fun isAdult(): Boolean { return age >= 18 } }
  29. class Admin(val name: String, val age: Int) : User {

    fun isAdult(): Boolean { return age >= 18 } }
  30. // data classes data class Admin(val name: String, val age:

    Int) // Automatically generates: - toString() - hashCode() / equals() - copy()
  31. Coroutines are computations that can be suspended without blocking a

    thread. https://kotlinlang.org/docs/tutorials/coroutines-basic-jvm.html
  32. //onCreate job = launch(background) { val result = requestData() launch(UI)

    { textViewHello.text = result } } //suspend function suspend fun requestData(): String { delay(3000) return "DONE" } //onDestroy job.cancel()
  33. //onCreate job = launch(background) { val result = requestData() launch(UI)

    { textViewHello.text = result } } //suspend function suspend fun requestData(): String { delay(3000) return "DONE" } //onDestroy job.cancel()
  34. //onCreate job = launch(background) { val result = requestData() launch(UI)

    { textViewHello.text = result } } //suspend function suspend fun requestData(): String { delay(3000) return "DONE" } //onDestroy job.cancel()
  35. //Before view.viewTreeObserver.addOnPreDrawListener( object : ViewTreeObserver.OnPreDrawListener { override fun onPreDraw(): Boolean

    { viewTreeObserver.removeOnPreDrawListener(this) actionToBeTriggered() return true } }) //After - with Android KTX view.doOnPreDraw { actionToBeTriggered() }
  36. Mocking - All classes in Kotlin are final unless you

    tell it otherwise (ie mark it as open ) - Workarounds but seem unnecessary https://antonioleiva.com/mockito-2-kotlin/ http://hadihariri.com/2016/10/04/Mocking-Kotlin-With-Mockito/
  37. Tooling IntelliJ is great… but it doesn’t write all the

    code. Battled with Lambda syntax, it sometimes doesn’t fll in all the blanks nicely Solution - Write it in Java, then copy paste the java into your Kotlin fle and it’ll auto convert
  38. Nothing, Unit & Any Nothing - never returns - ie

    infnite loop or exception throwing Unit - default return type for a function Any - Default Super Type (similar to Java’s Object type) http://natpryce.com/articles/000818.html
  39. Books • Kotlin in Action - Svetlana Isakova - Dmitry

    Jemerov • Kotlin for Android Developers - Some common patterns etc