idiomatic kotlin for android

36
Idiomatic Kotlin (with Android flavouring) Orion Health Auckland 24th June 2016

Upload: matthew-clarke

Post on 16-Apr-2017

169 views

Category:

Engineering


0 download

TRANSCRIPT

Idiomatic Kotlin(with Android flavouring)

Orion Health Auckland 24th June 2016

Idiomatic: Pronunciation: /ˌɪdɪəˈmatɪk/

ADJECTIVE

1 Using, containing, or denoting expressions that are natural to a native speaker

Or: Learning how to write Kotlin-y Kotlin instead of

Java-y Kotlin

Example: FragmentPagerAdapter

with 3 static pages

Java version

DRY violation!

Meaningful information

[

]

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”

[

]

Java attempt

Introduce a SAM (Single Abstract Method) interface:

DRY

Let’s see the calling code (e.g. Activity with a

ViewPager)…

• 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

Kotlin version

What is this as actual code?

“A list of things that return Fragments”

Kotlin = “A list of functions that return Fragments”

[

]

“A list of functions that return Fragments”

What does

look like in Kotlin?

Function that takes nothing and returns a Fragment:

List of functions that takes nothing and return a Fragment:

Lambda syntax to kill more boilerplate:

Type inference to kill more boilerplate:

Refactor constructor to accept a list of funcs

Replaced .get(n) call with index operator [n]

Replaced explicit .invoke() call with parentheses

Curly braces and return statement replaced with =

Return types removed, they can be inferred!

Let’s see the calling code (e.g. Activity with a

ViewPager)…

• 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