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

Migrating your Android App to Kotlin

Migrating your Android App to Kotlin

On Strategies to apply Kotlin to existing Java code

ravidsrk

August 13, 2017
Tweet

More Decks by ravidsrk

Other Decks in Programming

Transcript

  1. Steps to Convert Once you know 1. Convert files, one

    by one, via “⌥⇧⌘K”, make sure tests s ll pass 2. Go over the Kotlin files and make them more idioma c 3. Repeat step 2 un l you and your code reviewers are happy 4. Ship it
  2. Issues Interoperability Generated code is not always nice to look

    at ‼ Incrementally becoming more idioma c Companion Can Complicate Method Names star ng with get will give nightmares Genrics are hard to get it right No augument captor
  3. Takeaways annotationProcessor should be replaced by kapt Tests ease your

    mind Use mockito-kotlin to solve most of the issues faced while migra ng tests Reading less is not always a bad thing 29% less code compared to Java Configure tests to mock final classes
  4. Eliminate all !! from your Kotlin code 1. Use val

    instead of var 2. Use lateinit 3. Use let func on 4. Use Elvis operator 5. Use build‐in func ons requireNotNull or checkNotNull with accompanied excep on message for easy debugging.
  5. Use val instead of var Kotlin makes you think about

    immutability on the language level and that’s great. val is read‐only, var mutable. If you use them as immutables, you don’t have to care about nullability. Just beware that val can actually be mutable.
  6. Use lateinit private var mAdapter: RecyclerAdapter<Transaction>? = null override fun

    onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mAdapter = RecyclerAdapter(R.layout.item_transaction) } fun updateTransactions() { mAdapter!!.notifyDataSetChanged() }
  7. Use lateinit private lateinit var mAdapter: RecyclerAdapter<Transaction> override fun onCreate(savedInstanceState:

    Bundle?) { super.onCreate(savedInstanceState) mAdapter = RecyclerAdapter(R.layout.item_transaction) } fun updateTransactions() { mAdapter.notifyDataSetChanged() }
  8. Use let func on private var mPhotoUrl: String? = null

    fun uploadClicked() { if (mPhotoUrl != null) { uploadPhoto(mPhotoUrl!!) } } Replace with private var mPhotoUrl: String? = null fun uploadClicked() { mPhotoUrl?.let { uploadPhoto(it) } }
  9. Use Elvis operator fun getUserName(): String { if (mUserName !=

    null) { return mUserName!! } else { return "Anonymous" } } *Replace with fun getUserName(): String { return mUserName ?: "Anonymous" }