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

Kotlin for all the Droids

Kotlin for all the Droids

This talk will be around Kotlin being a first class language for Android. How it makes Android code much cleaner, better to maintain and introduces many new concepts that Android developers could not do in Java. This talk will be showing Android developers how to take their code to the next level.

Peter-John Welcome

March 29, 2018
Tweet

More Decks by Peter-John Welcome

Other Decks in Technology

Transcript

  1. Kotlin Was born in 2011 by JetBrains Team • Modern

    • Expressive • Magical • Powerful • Concise • Extensible https://en.wikipedia.org/wiki/Kotlin_(programming_language) 100% Interoperable with Java
  2. Why Kotlin over Java? • Java is very verbose. •

    Java Code is error prone with all its anonymous inner classes. • Java lacks modern language features. • Nullability issues.
  3. var/val var name : String = "Peter" name = "John"

    val surname = "Welcome" surname = "Johnson" // val can’t be reassigned
  4. Nullability var name : String = "Peter" name = null

    // null can’t be a value on a non-null String var surname : String? = "Peter" surname = null val otherName = surname ?: "" // Elvis operator ( ?? in other languages)
  5. Classes class User { private val name: String private val

    surname : String constructor(name : String , surname: String) { this .name = name this.surname = surname } } var user = User( surname = "Welcome", name = "Peter") // named arguments
  6. Data class @Parcelize data class Human (private var name: String,

    val age: Int) : Parcelable //copy, equal, hashcode, toString var human = Human("Peter",27)
  7. Sealed Classes sealed class Result<out T>{ data class Success<out T>

    (val value : T) : Result<T>() data class Error(val error : MyError) : Result<MyError>() }
  8. Sealed Classes fun <T>resultsFromService(result : Result<T>) : String { when

    (result) { is Result.Success -> "${result.value} World" is Result.Error -> return result.error.toString() } return "" } resultsFromService(Result.Success("Hello"))
  9. Functions fun hello(){ print("Hello") } val functionAsVariable = hello() val

    greetingPeter = fun (func : (name :String) -> String ) : String = func("Peter") greetingPeter { "Hello $it" }
  10. Extension functions infix fun Int.add (value : Int) = this

    + value val result = 1.add(1) val result = 1 add 1 //Extension function fun <T> Observable<T>.applySchedulers() : Observable<T> = this.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) //Usage disposable.add(this.viewModel.createPlant(Plant(name = "Best Plant Ever")).applySchedulers().subscribe ())
  11. Function Literals with Receiver inline fun SharedPreferences.edit(action: SharedPreferences.Editor.() -> Unit)

    { val editor = edit() editor.action() editor.apply() } getSharedPreferences("cache", Context.MODE_PRIVATE).edit { putString("username", "Peter") }
  12. Delegates var name : String by lazy { "Peter-John" }

    There are many more in the standard library and you can make your own. var surname : String by Delegates.observable("Welcome") { property, oldValue, newValue -> print(oldValue) // Welcome print(newValue) // Welcoming } surname = "Welcoming"
  13. AsyncTasks class doAsyncTask(textView: TextView) : AsyncTask<Unit, Unit, String>() { val

    innerTextView: TextView? = textView override fun doInBackground(vararg params: Unit?): String? { try { ... return data } catch (e: Exception) { return null } } override fun onPostExecute(result: String?) { super.onPostExecute(result) innerTextView?.text = JSONObject(result).toString() } }
  14. RxJava disposable.add(viewModel.fetchDashboardPlants() .applySchedulers() .subscribe({ //onNext: ... }, { error ->

    //onError }) ) fun <T> Observable<T>.applySchedulers() : Observable<T> = this.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
  15. Coroutines internal val background = newFixedThreadPoolContext(2, "background") launch (background) {

    val result = resultsFromService(Result.Success("Hello")) launch(UI) { this.textView.text = result } } // The async await way val someLongRunningTask = async<String>(CommonPool) { return@async "" }.await()
  16. Android KTX • Animator functions • Content • Time operations

    • OS • Utils (arrays, primitive types, File operations) • Database Cursor • Views, ViewGroup and Transitions • Graphics • And More https://medium.com/exploring-android/exploring-ktx-for-android-13a369795b51
  17. Android KTX //Normal Kotlin version view.viewTreeObserver.addOnPreDrawListener( object : ViewTreeObserver.OnPreDrawListener {

    override fun onPreDraw(): Boolean { viewTreeObserver.removeOnPreDrawListener(this) actionToBeTriggered() return true } }) //AndroidKTX version view.doOnPreDraw { actionToBeTriggered() }
  18. https://developer.android.com/guide/components/activities/intro-activities.html#kotlin Community Android Developer website • KotlinConf ( https://kotlinconf.com/ )

    • Kotlin Weekly ( http://kotlinweekly.net/ ) • Android Weekly ( http://androidweekly.net/ ) • Kotlin Slack ( http://slack.kotlinlang.org/ ) • Talking Kotlin - Podcast ( http://talkingkotlin.com/ )
  19. Links • https://www.youtube.com/playlist?list=PLQ176FUIyIUY6UK1cgVsbdPYA3X5 WLam5 • https://kotlinlang.org/docs/reference/android-overview.html • https://medium.com/exploring-android • http://talkingkotlin.com/

    • https://github.com/android/android-ktx • https://github.com/android/kotlin-guides • https://developer.android.com/kotlin/index.html • https://medium.com/@pjwelcome