SlideShare a Scribd company logo
Kotlin In Practice
彥彬
About me
Colorgy Android Developer
Taiwan Android Developer
Study Group(Android 讀書會)
1 year experience
Last year...
Kotlin in practice
General purpose
#1. Consider Android extension instead of
findViewById()
#1. Consider Android extension instead of
findViewById()
https://kotlinlang.org/docs/tutorials/android-plugin.html
#2. Avoid null and eliminate ‘!!’
private var adapter: CompanyItemAdapter? = null
...
adapter?.onItemClick = { ... }
private lateinit var adapter: CompanyItemAdapter
...
adapter.onItemClick = { ... }
#2. Avoid null and eliminate ‘!!’
private var repo: Repo? = null
...
if(repo == null){
repo = Repo()
}
repo!!.setId(id)
private var repo: Repo by lazy { repo = Repo() }
But !!
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
Val color = ContextCompat.getColor(context!!, R.color.white)
….
}
Can not be avoided
Creating Object
#3. Consider standard library to create
Collection
// old way of create a list
val items = ArrayList<Int>()
items.add(3)
items.add(4)
items.add(5)
// use standard library
val items = listOf(1, 2, 3)
val mutableItems = mutableListOf(1, 2, 3)
val map = mapOf(“key1” to 1, “key2” to 2)
#4. Use data class carefully
#4. Use data class carefully
Sometimes you don’t need them all
#5. Use apply{} to assign properties
// old way of building an object
val andre = Person()
andre.name = "andre"
andre.company = "Viacom"
andre.hobby = "losing in ping pong"
// after applying 'apply' (pun very much intended)
val andre = Person().apply {
name = "Andre"
company = "Viacom"
hobby = "losing in ping pong"
}
= Person()
andre.name = "andre
How about run, let, with, also?
the tldr; on Kotlin’s let, apply, also, with
and run functions
Still confusing?
Why not create your own extension
function?
public inline fun <T, R> T?.whenNotNull(block: () -> R?): R? {
return this?.let { block() }
}
foo.whenNotNull{
//do something
}
Lambda
#6. Consider lambda to implement callback
adapter.setOnItemClickListener { … }
interface OnItemClickListener{
fun onClick()
}
#6. Consider lambda to implement callback
adapter.setOnItemClickListener { … }
interface OnItemClickListener{
fun onClick()
}
We don’t need it!!
#6. Consider lambda to implement callback
adapter.onItemClick = { … }
class FooAdapter{
var onClick: (Item) -> Unit = {}
}
#7. Consider lambda to implement
strategy/template pattern
val typedArray = context.theme.obtainStyledAttributes(...)
try {
edgeLength = typedArray.getDimensionPixelSize(...)
charTextSize = typedArray.getDimensionPixelSize(...)
mainColor = typedArray.getColor(...)
textPadding = typedArray.getDimensionPixelSize(...)
}finally {
typedArray.recycle()
}
#7. Consider lambda to implement
strategy/template pattern
val typedArray = context.theme.obtainStyledAttributes(...)
try {
edgeLength = typedArray.getDimensionPixelSize(...)
charTextSize = typedArray.getDimensionPixelSize(...)
mainColor = typedArray.getColor(...)
textPadding = typedArray.getDimensionPixelSize(...)
}finally {
typedArray.recycle()
}
Don’t repeat yourself!!
#7. Consider lambda to implement
strategy/template pattern
use(typedArray) {
edgeLength = getDimensionPixelSize(...)
charTextSize = getDimensionPixelSize(...)
mainColor = getColor(...)
textPadding = getDimensionPixelSize(...)
}
#7. Consider lambda to implement
strategy/template pattern
fun use(typedArray: TypedArray, block : TypedArray.() -> Unit){
try {
typedArray.block()
}finally {
typedArray.recycle()
}
}
#7. Consider lambda to implement
strategy/template pattern
fun use(typedArray: TypedArray, block : TypedArray.() -> Unit){
try {
typedArray.block()
}finally {
typedArray.recycle()
}
}
Higher order function
Lambda with receiver
More about lambda design pattern(java)
https://www.youtube.com/watch?v=e4MT_Og
uDKg
Advanced topic
#8. Consider extension to enhance
Framework Apis
● Dp to px
● OnPreDraw
● postDelayedSafely
Dp to px
private val padding= 16.toPx()
Dp to px
private val padding= 16.toPx()
fun Int.toPx(): Int = (this * Resources.getSystem().displayMetrics.density).toInt()
OnPreDraw
view.viewTreeObserver.addOnPreDrawListener(
object : ViewTreeObserver.OnPreDrawListener {
override fun onPreDraw(): Boolean {
viewTreeObserver.removeOnPreDrawListener(this)
actionToBeTriggered()
return true
}
})
OnPreDraw
view.viewTreeObserver.addOnPreDrawListener(
object : ViewTreeObserver.OnPreDrawListener {
override fun onPreDraw(): Boolean {
viewTreeObserver.removeOnPreDrawListener(this)
actionToBeTriggered()
return true
}
})
OnPreDraw
view.doOnPreDraw {
actionToBeTriggered()
}
Post Delayed
Class FooFragment{
fun doSomething(){
view?.postDelayed({
txtLabel.text = "123"
}, 2000)
}
}
Post Delayed
Class FooFragment{
fun doSomething(){
view?.postDelayed({
txtLabel.text = "123"
}, 2000)
}
} potential NullPointer !!
Post Delayed
Class FooFragment{
fun doSomething(){
view?.postDelayed({
if(isAdded){
txtLabel.text = "123"
}
}, 2000)
}
}
Post Delayed
Class FooFragment{
fun doSomething(){
postDelayedSafely({
txtLabel.text = "123"
}, 2000)
}
}
Post Delayed
Class FooFragment{
fun doSomething(){
postDelayedSafely({
txtLabel.text = "123"
}, 2000)
}
}
fun Fragment.postDelaySafely(action: ()-> Unit, delayMillis: Long){
view?.postDelayed({
if(isAdded){
action()
}
}, delayMillis)
}
More on Android - ktx
https://github.com/android/android-ktx
Do not extend you own code!!
● You can control everything
● Extensions is hard to test
#9. Consider refied to replace ::class.java
inline fun <reified T> Gson.fromJson(jsonString: String?): T?{
val type = object : TypeToken<T>() {}.type
return fromJson<T>(jsonString, type)
}
val items: List<Item>? = gson.fromJson<List<Item>>(jsonString)
#10. DSL makes your life easier
toolbarSetup(toolbar) {
title("")
homeIcon(R.drawable.back_white)
backgroundColor(R.color.calendar_today_background)
onHomeClicked { pageNavigator.toLastPage() }
}
DSL? Things you need to know
1. Extensions function
2. Lambda with receiver
3. Operator overloading
4. Generic
5. Infix
6. Invoke operator
Resources
1. Kotlin Weekly
2. Official Documentation
3. Youtube
a. Google I/O
4. Medium
a. Effective Java in Kotlin
b. Coroutines and RxJava
5.
Any Question?

More Related Content

Similar to Kotlin in practice (20)

PDF
Blocks by Lachs Cox
lachie
 
PDF
The Naked Bundle - Symfony Live London 2014
Matthias Noback
 
PDF
Android UI Tips, Tricks and Techniques
Marakana Inc.
 
PDF
Android UI Development: Tips, Tricks, and Techniques
Edgar Gonzalez
 
PDF
Object Oriented Views / Aki Salmi
Aki Salmi
 
PPT
Practices For Becoming A Better Programmer
Srikanth Shreenivas
 
PPT
Cocoa for Web Developers
georgebrock
 
PPT
C++tutorial
dips17
 
PDF
The Naked Bundle - Symfony Barcelona
Matthias Noback
 
PPT
Object Orientation vs. Functional Programming in Python
Python Ireland
 
PDF
Dominate The Theme Layer
Jesper Wøldiche
 
KEY
A tour on ruby and friends
旻琦 潘
 
PDF
Introduction to React Native Workshop
Ignacio Martín
 
PDF
The Naked Bundle - Symfony Usergroup Belgium
Matthias Noback
 
PPTX
“Insulin” for Scala’s Syntactic Diabetes
Tzach Zohar
 
PPTX
Software System Architecture-Lecture 6.pptx
ssuser9a23691
 
PPT
DSL - expressive syntax on top of a clean semantic model
Debasish Ghosh
 
PDF
Alloy Tips & Tricks #TiLon
Fokke Zandbergen
 
PDF
How to write Ruby extensions with Crystal
Anna (gaar4ica) Shcherbinina
 
KEY
あたかも自然言語を書くようにコーディングしてみる
Kazuya Numata
 
Blocks by Lachs Cox
lachie
 
The Naked Bundle - Symfony Live London 2014
Matthias Noback
 
Android UI Tips, Tricks and Techniques
Marakana Inc.
 
Android UI Development: Tips, Tricks, and Techniques
Edgar Gonzalez
 
Object Oriented Views / Aki Salmi
Aki Salmi
 
Practices For Becoming A Better Programmer
Srikanth Shreenivas
 
Cocoa for Web Developers
georgebrock
 
C++tutorial
dips17
 
The Naked Bundle - Symfony Barcelona
Matthias Noback
 
Object Orientation vs. Functional Programming in Python
Python Ireland
 
Dominate The Theme Layer
Jesper Wøldiche
 
A tour on ruby and friends
旻琦 潘
 
Introduction to React Native Workshop
Ignacio Martín
 
The Naked Bundle - Symfony Usergroup Belgium
Matthias Noback
 
“Insulin” for Scala’s Syntactic Diabetes
Tzach Zohar
 
Software System Architecture-Lecture 6.pptx
ssuser9a23691
 
DSL - expressive syntax on top of a clean semantic model
Debasish Ghosh
 
Alloy Tips & Tricks #TiLon
Fokke Zandbergen
 
How to write Ruby extensions with Crystal
Anna (gaar4ica) Shcherbinina
 
あたかも自然言語を書くようにコーディングしてみる
Kazuya Numata
 

More from 彥彬 洪 (13)

PDF
Rx java testing patterns
彥彬 洪
 
PDF
Rxjava2 custom operator
彥彬 洪
 
PDF
Koin
彥彬 洪
 
PDF
Android material theming
彥彬 洪
 
PDF
Why use dependency injection
彥彬 洪
 
PDF
Jsr310
彥彬 洪
 
PDF
ThreeTen
彥彬 洪
 
PDF
科特林λ學
彥彬 洪
 
PDF
Mvp in practice
彥彬 洪
 
PDF
Green dao 3.0
彥彬 洪
 
PDF
Android 6.0 permission change
彥彬 洪
 
PDF
設定android 測試環境
彥彬 洪
 
PDF
Green dao
彥彬 洪
 
Rx java testing patterns
彥彬 洪
 
Rxjava2 custom operator
彥彬 洪
 
Android material theming
彥彬 洪
 
Why use dependency injection
彥彬 洪
 
Jsr310
彥彬 洪
 
ThreeTen
彥彬 洪
 
科特林λ學
彥彬 洪
 
Mvp in practice
彥彬 洪
 
Green dao 3.0
彥彬 洪
 
Android 6.0 permission change
彥彬 洪
 
設定android 測試環境
彥彬 洪
 
Green dao
彥彬 洪
 
Ad

Recently uploaded (20)

PPTX
Build a Custom Agent for Agentic Testing.pptx
klpathrudu
 
PDF
Meet in the Middle: Solving the Low-Latency Challenge for Agentic AI
Alluxio, Inc.
 
PDF
Is Framer the Future of AI Powered No-Code Development?
Isla Pandora
 
PDF
Best Web development company in india 2025
Greenusys
 
PDF
How to Hire AI Developers_ Step-by-Step Guide in 2025.pdf
DianApps Technologies
 
PDF
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
PPTX
From spreadsheets and delays to real-time control
SatishKumar2651
 
PDF
MiniTool Power Data Recovery 8.8 With Crack New Latest 2025
bashirkhan333g
 
PDF
Ready Layer One: Intro to the Model Context Protocol
mmckenna1
 
PDF
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
PPTX
Function & Procedure: Function Vs Procedure in PL/SQL
Shani Tiwari
 
PPTX
Get Started with Maestro: Agent, Robot, and Human in Action – Session 5 of 5
klpathrudu
 
PDF
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
PPTX
BB FlashBack Pro 5.61.0.4843 With Crack Free Download
cracked shares
 
PDF
Dipole Tech Innovations – Global IT Solutions for Business Growth
dipoletechi3
 
PDF
AI Prompts Cheat Code prompt engineering
Avijit Kumar Roy
 
PDF
ERP Consulting Services and Solutions by Contetra Pvt Ltd
jayjani123
 
PPTX
Library_Management_System_PPT111111.pptx
nmtnissancrm
 
PDF
UITP Summit Meep Pitch may 2025 MaaS Rebooted
campoamor1
 
PPTX
Prompt Like a Pro. Leveraging Salesforce Data to Power AI Workflows.pptx
Dele Amefo
 
Build a Custom Agent for Agentic Testing.pptx
klpathrudu
 
Meet in the Middle: Solving the Low-Latency Challenge for Agentic AI
Alluxio, Inc.
 
Is Framer the Future of AI Powered No-Code Development?
Isla Pandora
 
Best Web development company in india 2025
Greenusys
 
How to Hire AI Developers_ Step-by-Step Guide in 2025.pdf
DianApps Technologies
 
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
From spreadsheets and delays to real-time control
SatishKumar2651
 
MiniTool Power Data Recovery 8.8 With Crack New Latest 2025
bashirkhan333g
 
Ready Layer One: Intro to the Model Context Protocol
mmckenna1
 
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
Function & Procedure: Function Vs Procedure in PL/SQL
Shani Tiwari
 
Get Started with Maestro: Agent, Robot, and Human in Action – Session 5 of 5
klpathrudu
 
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
BB FlashBack Pro 5.61.0.4843 With Crack Free Download
cracked shares
 
Dipole Tech Innovations – Global IT Solutions for Business Growth
dipoletechi3
 
AI Prompts Cheat Code prompt engineering
Avijit Kumar Roy
 
ERP Consulting Services and Solutions by Contetra Pvt Ltd
jayjani123
 
Library_Management_System_PPT111111.pptx
nmtnissancrm
 
UITP Summit Meep Pitch may 2025 MaaS Rebooted
campoamor1
 
Prompt Like a Pro. Leveraging Salesforce Data to Power AI Workflows.pptx
Dele Amefo
 
Ad

Kotlin in practice

  • 2. About me Colorgy Android Developer Taiwan Android Developer Study Group(Android 讀書會) 1 year experience
  • 6. #1. Consider Android extension instead of findViewById()
  • 7. #1. Consider Android extension instead of findViewById() https://kotlinlang.org/docs/tutorials/android-plugin.html
  • 8. #2. Avoid null and eliminate ‘!!’ private var adapter: CompanyItemAdapter? = null ... adapter?.onItemClick = { ... } private lateinit var adapter: CompanyItemAdapter ... adapter.onItemClick = { ... }
  • 9. #2. Avoid null and eliminate ‘!!’ private var repo: Repo? = null ... if(repo == null){ repo = Repo() } repo!!.setId(id) private var repo: Repo by lazy { repo = Repo() }
  • 10. But !! override fun onViewCreated(view: View, savedInstanceState: Bundle?) { Val color = ContextCompat.getColor(context!!, R.color.white) …. } Can not be avoided
  • 12. #3. Consider standard library to create Collection // old way of create a list val items = ArrayList<Int>() items.add(3) items.add(4) items.add(5) // use standard library val items = listOf(1, 2, 3) val mutableItems = mutableListOf(1, 2, 3) val map = mapOf(“key1” to 1, “key2” to 2)
  • 13. #4. Use data class carefully
  • 14. #4. Use data class carefully
  • 15. Sometimes you don’t need them all
  • 16. #5. Use apply{} to assign properties // old way of building an object val andre = Person() andre.name = "andre" andre.company = "Viacom" andre.hobby = "losing in ping pong" // after applying 'apply' (pun very much intended) val andre = Person().apply { name = "Andre" company = "Viacom" hobby = "losing in ping pong" } = Person() andre.name = "andre
  • 17. How about run, let, with, also? the tldr; on Kotlin’s let, apply, also, with and run functions
  • 19. Why not create your own extension function? public inline fun <T, R> T?.whenNotNull(block: () -> R?): R? { return this?.let { block() } } foo.whenNotNull{ //do something }
  • 21. #6. Consider lambda to implement callback adapter.setOnItemClickListener { … } interface OnItemClickListener{ fun onClick() }
  • 22. #6. Consider lambda to implement callback adapter.setOnItemClickListener { … } interface OnItemClickListener{ fun onClick() } We don’t need it!!
  • 23. #6. Consider lambda to implement callback adapter.onItemClick = { … } class FooAdapter{ var onClick: (Item) -> Unit = {} }
  • 24. #7. Consider lambda to implement strategy/template pattern val typedArray = context.theme.obtainStyledAttributes(...) try { edgeLength = typedArray.getDimensionPixelSize(...) charTextSize = typedArray.getDimensionPixelSize(...) mainColor = typedArray.getColor(...) textPadding = typedArray.getDimensionPixelSize(...) }finally { typedArray.recycle() }
  • 25. #7. Consider lambda to implement strategy/template pattern val typedArray = context.theme.obtainStyledAttributes(...) try { edgeLength = typedArray.getDimensionPixelSize(...) charTextSize = typedArray.getDimensionPixelSize(...) mainColor = typedArray.getColor(...) textPadding = typedArray.getDimensionPixelSize(...) }finally { typedArray.recycle() } Don’t repeat yourself!!
  • 26. #7. Consider lambda to implement strategy/template pattern use(typedArray) { edgeLength = getDimensionPixelSize(...) charTextSize = getDimensionPixelSize(...) mainColor = getColor(...) textPadding = getDimensionPixelSize(...) }
  • 27. #7. Consider lambda to implement strategy/template pattern fun use(typedArray: TypedArray, block : TypedArray.() -> Unit){ try { typedArray.block() }finally { typedArray.recycle() } }
  • 28. #7. Consider lambda to implement strategy/template pattern fun use(typedArray: TypedArray, block : TypedArray.() -> Unit){ try { typedArray.block() }finally { typedArray.recycle() } } Higher order function Lambda with receiver
  • 29. More about lambda design pattern(java) https://www.youtube.com/watch?v=e4MT_Og uDKg
  • 31. #8. Consider extension to enhance Framework Apis ● Dp to px ● OnPreDraw ● postDelayedSafely
  • 32. Dp to px private val padding= 16.toPx()
  • 33. Dp to px private val padding= 16.toPx() fun Int.toPx(): Int = (this * Resources.getSystem().displayMetrics.density).toInt()
  • 34. OnPreDraw view.viewTreeObserver.addOnPreDrawListener( object : ViewTreeObserver.OnPreDrawListener { override fun onPreDraw(): Boolean { viewTreeObserver.removeOnPreDrawListener(this) actionToBeTriggered() return true } })
  • 35. OnPreDraw view.viewTreeObserver.addOnPreDrawListener( object : ViewTreeObserver.OnPreDrawListener { override fun onPreDraw(): Boolean { viewTreeObserver.removeOnPreDrawListener(this) actionToBeTriggered() return true } })
  • 37. Post Delayed Class FooFragment{ fun doSomething(){ view?.postDelayed({ txtLabel.text = "123" }, 2000) } }
  • 38. Post Delayed Class FooFragment{ fun doSomething(){ view?.postDelayed({ txtLabel.text = "123" }, 2000) } } potential NullPointer !!
  • 39. Post Delayed Class FooFragment{ fun doSomething(){ view?.postDelayed({ if(isAdded){ txtLabel.text = "123" } }, 2000) } }
  • 40. Post Delayed Class FooFragment{ fun doSomething(){ postDelayedSafely({ txtLabel.text = "123" }, 2000) } }
  • 41. Post Delayed Class FooFragment{ fun doSomething(){ postDelayedSafely({ txtLabel.text = "123" }, 2000) } } fun Fragment.postDelaySafely(action: ()-> Unit, delayMillis: Long){ view?.postDelayed({ if(isAdded){ action() } }, delayMillis) }
  • 42. More on Android - ktx https://github.com/android/android-ktx
  • 43. Do not extend you own code!! ● You can control everything ● Extensions is hard to test
  • 44. #9. Consider refied to replace ::class.java inline fun <reified T> Gson.fromJson(jsonString: String?): T?{ val type = object : TypeToken<T>() {}.type return fromJson<T>(jsonString, type) } val items: List<Item>? = gson.fromJson<List<Item>>(jsonString)
  • 45. #10. DSL makes your life easier toolbarSetup(toolbar) { title("") homeIcon(R.drawable.back_white) backgroundColor(R.color.calendar_today_background) onHomeClicked { pageNavigator.toLastPage() } }
  • 46. DSL? Things you need to know 1. Extensions function 2. Lambda with receiver 3. Operator overloading 4. Generic 5. Infix 6. Invoke operator
  • 47. Resources 1. Kotlin Weekly 2. Official Documentation 3. Youtube a. Google I/O 4. Medium a. Effective Java in Kotlin b. Coroutines and RxJava 5.