Idiomatic Kotlin for Android
-
Upload
matthew-clarke -
Category
Engineering
-
view
172 -
download
0
Transcript of Idiomatic Kotlin for Android
Idiomatic: Pronunciation: /ˌɪdɪəˈmatɪk/
ADJECTIVE
1 Using, containing, or denoting expressions that are natural to a native speaker
[
]
Objective (pseudo-code)
• Pass just the meaningful info to a new adapter • Reduce noise/kill boilerplate • Don’t repeat ourselves
What is this as actual code?
“A list of things that return Fragments”
Java = “A list of objects that return Fragments”
[
]
• Pass just the meaningful info to a new adapter • Reduce noise/kill boilerplate • Don’t repeat ourselves
Java version
✔
✔❌
Java version• Achieved DRY but…
• Far more boilerplate than the original!
• And worse, boilerplate is in calling code rather than hidden in implementation (anonymous inner classes)
• Conclusion: not worth it. Stick with adapter coupled to concrete fragments
What is this as actual code?
“A list of things that return Fragments”
Kotlin = “A list of functions that return Fragments”
[
]
• Pass just the meaningful info to a new adapter • Reduce noise/kill boilerplate • Don’t repeat ourselves
Kotlin version
✔
✔✔
Recap• Function types - passing functions as parameters
• Lambda (function literal) syntax { OnboardingFragment() }
• Type inference
• Indexing operator .get(n) -> []
• Invoke operator .invoke() -> ()
Conclusion
• Reduce your (Java-imposed) tolerance to boilerplate. It’s even more of a code smell in Kotlin!
• Lots of language tools to kill boilerplate!
• Passing functions around is new territory, be creative
Matthew Clarke Oblig twitter handle: @kiwiandroiddev References:https://kotlinlang.org/docs/reference/operator-overloading.html
Thank you