SlideShare a Scribd company logo
Miracle of stdLib
Pop @ Shopspot
Ju @ Agoda
Apply, Also, With, Let, Run
Apply, Also, With
fun initTextView(context: Context) {
val tvJAV = TextView(context)
tvJAV.setText(R.string.app_name)
tvJAV.setTextColor(ContextCompat.getColor(context, R.color.colorPrimary))
tvJAV.setOnClickListener {
Toast.makeText(context, "Hello JAV", Toast.LENGTH_SHORT).show()
}
}
Java Style
Apply, Also, With
fun initTextView(context: Context) {
val tvJAV = TextView(context).apply {
//this in this block is tvJAV scope
setText(R.string.app_name)
setTextColor(ContextCompat.getColor(context, R.color.colorPrimary))
setOnClickListener {
Toast.makeText(context, "Hello JAV", Toast.LENGTH_SHORT).show()
}
}
}
Apply
Apply, Also, With
Also
fun initTextView(context: Context) {
val tvJAV = TextView(context).also {
//it or can assign new name
it.setText(R.string.app_name)
it.setTextColor(ContextCompat.getColor(context, R.color.colorPrimary))
it.setOnClickListener {
Toast.makeText(context, "Hello JAV", Toast.LENGTH_SHORT).show()
}
}
}
Apply, Also, With
With
fun initTextView(context: Context) {
val textViewText = with(textView) {
setText(R.string.app_name)
setTextColor(ContextCompat.getColor(context, R.color.colorPrimary))
setOnClickListener{
Toast.makeText(context, "Hello JAV", Toast.LENGTH_SHORT).show()
}
// Last statement is return value
text
}
// textViewText = "Miracle of stdLib"
}
Let, Run
fun callApi(callback: ((String) -> Unit)? = null) {
val resultString: String? = "" //TODO: Call API and get String result
if (resultString != null && callback != null) {
callback.invoke(resultString)
}
}
Java Style
fun callApi(callback: ((String) -> Unit)? = null) {
val resultString: String? = ""//TODO: Call API and get String result
resultString?.let { success?.invoke(it) }
// or
resultString?.run { success?.invoke(this) }
}
Kotlin Style
Let, Run
fun sumPair() {
val pair: Pair<Int, Int>? = Pair(3, 5)
var sum = if (pair != null) pair.first + pair.second else 0
}
Java Style
fun sumPair() {
val pair: Pair<Int, Int>? = Pair(3, 5)
val sumRun = pair?.run { first + second } ?: 0
// or
val sumLet = pair?.let { it.first + it.second } ?: 0
}
Kotlin Style
Quiz ?
Delegates
Lazy
class FakeFragment : Fragment() {
// This approach can not run cuz ...
val badPreference = context.getSharedPreferences(...)
lateinit var lateInitPreference: SharedPreferences
val lazyPreference: SharedPreferences by lazy { context.getSharedPreferences(...) }
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
lateInitPreference = context.getSharedPreferences(...)
lateInitPreference.getString("LATEINIT_PREFERENCE", ":|")
lazyPreference.getString("LAZY_PREFERENCE", ":)")
}
}
Observable
class HelloObservable {
var name by Delegates.observable("time0") { _, old, new ->
println("New $new, Old $old")
}
fun run() {
name = "time1" // New time1, Old time0
name = "time2" // New time2, Old time1
name = "time3" // New time3, Old time2
name = "time5" // New time5, Old time3
name = "time6" // New time6, Old time5
}
}
Vetoable
class HelloVetoable {
var age by Delegates.vetoable(0) { _, old, new ->
println("New $new, Old $old")
new < 10
}
fun run() {
age = 1 // age = 1
age = 2 // age = 2
age = 10 // age = 2
age = 1000 // age = 2
}
}
Collections
Type
val list = listOf(1, 2, 3) // [1, 2, 3]
val set = setOf("Ant", "Bat", "Cat", "Ant", "Bat") // [Ant, Bat, Cat]
val map = mapOf("A" to 1, "B" to 2) // {"A":1, "B":2}
val range = 1..5 // [1, 2, 3, 4, 5]
val rangeChar = 'A'..'C' // ['A', 'B', 'C']
Immutable
val list = mutableListOf("A", "B", "C", "A", "B") // [A, B, C, A, B]
list.add("D") // [A, B, C, A, B, D]
list.add(0, "Z") // [Z, A, B, C, A, B, D]
list.removeAt(1) // [Z, B, C, A, B, D]
val set = mutableSetOf("A", "B", "C", "A", "B") // [A, B, C]
val map = mutableMapOf("A" to 1, "B" to 2) // {"A":1, "B":2}
map.remove("C") // {"A":1, "B":2}
Mutable
Extension Function
val list = listOf(1, 2, 3)
list.all { it > 0 } // true
list.any { it < 0 } // false
list.none { it > 5 } // false
list.joinToString("Kotlin") // 1Kotlin2Kotlin3
list.sum() // 6
set.sumBy { it.length } // 9
map.minBy { it.value } // {"A":1}
3 in range // true
range.sum() // 15
// Loop
for (i in 0..list.size - 1) {
list[i]
}
list.forEach { item -> }
list.forEachIndexed { index, item -> }
// Convert Type
list.toSet()
set.toMutableList()
map.toList()
range.toList()
Extension Function (Operator/Infix)
val list1 = listOf(1, 2, 3) // [1, 2, 3]
val list2 = listOf(3, 4) // [3, 4]
val listPlus = list1 + list2 // [1, 2, 3, 3, 4]
val listMinus = list1 - list2 // [1, 2]
val listContain = 1 in list1 // true
val listUnion = list1 union list2 // [1, 2, 3, 4]
val listIntersect = list1 intersect list2 // [3]
val listSubtract = list1 subtract list2 // [1, 2]
val listZip = list1 zip list2 // [(1, 3), (2, 4)]
Operator Infix
Data Model
data class Category(val id: String,
val name: String,
val subCategoryList: List<Category> = listOf())
data class Product(val id: String,
val name: String,
val description: String,
val price: Double,
val category: Category)
Search One Item
private val categoryList = listOf(Category("1", "sport"))
private val productList = listOf(
Product("1", "product1", "description1", 100.0, categoryList[0]),
Product("2", "product2", "description2", 200.0, categoryList[0]),
Product("3", "product3", "description3", 300.0, categoryList[0]),
Product("4", "product4", "description4", 400.0, categoryList[0]),
Product("5", "product5", "description5", 200.0, categoryList[0]),
Product("6", "product6", "description6", 600.0, categoryList[0])
)
fun search_one() {
productList.first() // Product 1
productList.first { it.name == "product20" } // Throw NoSuchElementException
productList.firstOrNull { it.price == 200.0 } // Product 2
productList.firstOrNull { it.price == 1000.0 } // Null
productList.last() // Product 6
productList.lastOrNull { it.price == 200.0 } // Product 5
productList.single() // throw IllegalArgumentException("List has more than one element.")
productList.singleOrNull() // Null
productList.single { it.price == 600.0 } // Product 6
productList.single { it.price == 200.0 } // throw IllegalArgumentException("Collection contains more than one
matching element.")
}
Advance
private val categoryList = listOf(
Category("1", "sport1", listOf(
Category("4", "sport4"),
Category("5", "sport5")
)),
Category("2", "sport2", listOf(
Category("6", "sport6")
)),
Category("3", "sport3")
)
private val productList = listOf(
Product("1", "product1", "description1", 100.0,
categoryList[0]),
Product("2", "product2", "description5", 200.0,
categoryList[1]),
Product("3", "product3", "description3", 300.0,
categoryList[2]),
Product("4", "product4", "description4", 400.0,
categoryList[1]),
Product("5", "product5", "description2", 200.0,
categoryList[0]),
Product("6", "product6", "description6", 600.0,
categoryList[2])
)
fun advance_collection() {
productList.filter { it.price > 200.0 } // 3,4,6
productList.filterNot { it.price == 200.0 } //
1,3,4,6
productList.map { it.price * 1.07 } // 107.0, 214.0
,321.0, 428.0, 214.0, 642.0 vat7%
categoryList.flatMap {
it.subCategoryList.map { it.name } // [sport4,
sport5], [sport6], []
} // [sport4, sport5, sport6]
productList.groupBy { it.category } // {cat1:[p1,p5],
cat2:[p2,p4], cat3:[p3,p6]
productList.sortedBy { it.price } //
[p1,p2,p5,p3,p4,p6]
productList.sortedByDescending { it.price }
//[p6,p4,p3,p5,p2,p1]
productList.sortedWith(compareBy(Product::price,
Product::description)) // [p1,p5,p2,p3,p4,p6]
}
Quiz ?
Sponsors by:

More Related Content

What's hot

Stubる - Mockingjayを使ったHTTPクライアントのテスト -
Stubる - Mockingjayを使ったHTTPクライアントのテスト -Stubる - Mockingjayを使ったHTTPクライアントのテスト -
Stubる - Mockingjayを使ったHTTPクライアントのテスト -
Kenji Tanaka
 
ES6 in Real Life
ES6 in Real LifeES6 in Real Life
ES6 in Real Life
Domenic Denicola
 
EcmaScript 6
EcmaScript 6 EcmaScript 6
EcmaScript 6
Manoj Kumar
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
Manoj Kumar
 
Swiftの関数型っぽい部分
Swiftの関数型っぽい部分Swiftの関数型っぽい部分
Swiftの関数型っぽい部分
bob_is_strange
 
Poor Man's Functional Programming
Poor Man's Functional ProgrammingPoor Man's Functional Programming
Poor Man's Functional ProgrammingDmitry Buzdin
 
Nice to meet Kotlin
Nice to meet KotlinNice to meet Kotlin
Nice to meet Kotlin
Jieyi Wu
 
多治見IT勉強会 Groovy Grails
多治見IT勉強会 Groovy Grails多治見IT勉強会 Groovy Grails
多治見IT勉強会 Groovy Grails
Tsuyoshi Yamamoto
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 SpringKiyotaka Oku
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
Pavlo Baron
 
Sneaking inside Kotlin features
Sneaking inside Kotlin featuresSneaking inside Kotlin features
Sneaking inside Kotlin features
Chandra Sekhar Nayak
 
Jakarta Commons - Don't re-invent the wheel
Jakarta Commons - Don't re-invent the wheelJakarta Commons - Don't re-invent the wheel
Jakarta Commons - Don't re-invent the wheel
tcurdt
 
No dark magic - Byte code engineering in the real world
No dark magic - Byte code engineering in the real worldNo dark magic - Byte code engineering in the real world
No dark magic - Byte code engineering in the real world
tcurdt
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is here
Sebastiano Armeli
 
Javascript ES6 generators
Javascript ES6 generatorsJavascript ES6 generators
Javascript ES6 generators
Ramesh Nair
 
Ian 20150116 java script oop
Ian 20150116 java script oopIan 20150116 java script oop
Ian 20150116 java script oop
LearningTech
 
Apache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheelApache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheel
tcurdt
 

What's hot (19)

Stubる - Mockingjayを使ったHTTPクライアントのテスト -
Stubる - Mockingjayを使ったHTTPクライアントのテスト -Stubる - Mockingjayを使ったHTTPクライアントのテスト -
Stubる - Mockingjayを使ったHTTPクライアントのテスト -
 
ES6 in Real Life
ES6 in Real LifeES6 in Real Life
ES6 in Real Life
 
EcmaScript 6
EcmaScript 6 EcmaScript 6
EcmaScript 6
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
 
Swiftの関数型っぽい部分
Swiftの関数型っぽい部分Swiftの関数型っぽい部分
Swiftの関数型っぽい部分
 
Poor Man's Functional Programming
Poor Man's Functional ProgrammingPoor Man's Functional Programming
Poor Man's Functional Programming
 
Nice to meet Kotlin
Nice to meet KotlinNice to meet Kotlin
Nice to meet Kotlin
 
多治見IT勉強会 Groovy Grails
多治見IT勉強会 Groovy Grails多治見IT勉強会 Groovy Grails
多治見IT勉強会 Groovy Grails
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 Spring
 
ECMAScript 6
ECMAScript 6ECMAScript 6
ECMAScript 6
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
Sneaking inside Kotlin features
Sneaking inside Kotlin featuresSneaking inside Kotlin features
Sneaking inside Kotlin features
 
Jakarta Commons - Don't re-invent the wheel
Jakarta Commons - Don't re-invent the wheelJakarta Commons - Don't re-invent the wheel
Jakarta Commons - Don't re-invent the wheel
 
No dark magic - Byte code engineering in the real world
No dark magic - Byte code engineering in the real worldNo dark magic - Byte code engineering in the real world
No dark magic - Byte code engineering in the real world
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is here
 
Javascript ES6 generators
Javascript ES6 generatorsJavascript ES6 generators
Javascript ES6 generators
 
Ian 20150116 java script oop
Ian 20150116 java script oopIan 20150116 java script oop
Ian 20150116 java script oop
 
Apache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheelApache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheel
 
Hw09 Hadoop + Clojure
Hw09   Hadoop + ClojureHw09   Hadoop + Clojure
Hw09 Hadoop + Clojure
 

Similar to Miracle of std lib

ddd+scala
ddd+scaladdd+scala
ddd+scala
潤一 加藤
 
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf MilanFrom Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
Fabio Collini
 
Kotlin collections
Kotlin collectionsKotlin collections
Kotlin collections
Myeongin Woo
 
An Introduction to Scala (2014)
An Introduction to Scala (2014)An Introduction to Scala (2014)
An Introduction to Scala (2014)
William Narmontas
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기
진성 오
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
Aleksandar Prokopec
 
여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language
Ashal aka JOKER
 
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin WayTDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
tdc-globalcode
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecLoïc Descotte
 
かとうの Kotlin 講座 こってり版
かとうの Kotlin 講座 こってり版かとうの Kotlin 講座 こってり版
かとうの Kotlin 講座 こってり版
Yutaka Kato
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner code
Mite Mitreski
 
Kotlin : Advanced Tricks - Ubiratan Soares
Kotlin : Advanced Tricks - Ubiratan SoaresKotlin : Advanced Tricks - Ubiratan Soares
Kotlin : Advanced Tricks - Ubiratan Soares
iMasters
 
Transaction is a monad
Transaction is a  monadTransaction is a  monad
Transaction is a monad
Jarek Ratajski
 
ハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使うハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使う
bpstudy
 
Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2
Kirill Rozov
 
Kotlin, why?
Kotlin, why?Kotlin, why?
Kotlin, why?
Paweł Byszewski
 
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Codemotion
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 World
BTI360
 
Kotlin
KotlinKotlin
code for quiz in my sql
code for quiz  in my sql code for quiz  in my sql
code for quiz in my sql
JOYITAKUNDU1
 

Similar to Miracle of std lib (20)

ddd+scala
ddd+scaladdd+scala
ddd+scala
 
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf MilanFrom Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
 
Kotlin collections
Kotlin collectionsKotlin collections
Kotlin collections
 
An Introduction to Scala (2014)
An Introduction to Scala (2014)An Introduction to Scala (2014)
An Introduction to Scala (2014)
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language
 
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin WayTDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 
かとうの Kotlin 講座 こってり版
かとうの Kotlin 講座 こってり版かとうの Kotlin 講座 こってり版
かとうの Kotlin 講座 こってり版
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner code
 
Kotlin : Advanced Tricks - Ubiratan Soares
Kotlin : Advanced Tricks - Ubiratan SoaresKotlin : Advanced Tricks - Ubiratan Soares
Kotlin : Advanced Tricks - Ubiratan Soares
 
Transaction is a monad
Transaction is a  monadTransaction is a  monad
Transaction is a monad
 
ハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使うハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使う
 
Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2
 
Kotlin, why?
Kotlin, why?Kotlin, why?
Kotlin, why?
 
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 World
 
Kotlin
KotlinKotlin
Kotlin
 
code for quiz in my sql
code for quiz  in my sql code for quiz  in my sql
code for quiz in my sql
 

Recently uploaded

Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
timhan337
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
EduSkills OECD
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 

Recently uploaded (20)

Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 

Miracle of std lib

  • 1. Miracle of stdLib Pop @ Shopspot Ju @ Agoda
  • 3. Apply, Also, With fun initTextView(context: Context) { val tvJAV = TextView(context) tvJAV.setText(R.string.app_name) tvJAV.setTextColor(ContextCompat.getColor(context, R.color.colorPrimary)) tvJAV.setOnClickListener { Toast.makeText(context, "Hello JAV", Toast.LENGTH_SHORT).show() } } Java Style
  • 4. Apply, Also, With fun initTextView(context: Context) { val tvJAV = TextView(context).apply { //this in this block is tvJAV scope setText(R.string.app_name) setTextColor(ContextCompat.getColor(context, R.color.colorPrimary)) setOnClickListener { Toast.makeText(context, "Hello JAV", Toast.LENGTH_SHORT).show() } } } Apply
  • 5. Apply, Also, With Also fun initTextView(context: Context) { val tvJAV = TextView(context).also { //it or can assign new name it.setText(R.string.app_name) it.setTextColor(ContextCompat.getColor(context, R.color.colorPrimary)) it.setOnClickListener { Toast.makeText(context, "Hello JAV", Toast.LENGTH_SHORT).show() } } }
  • 6. Apply, Also, With With fun initTextView(context: Context) { val textViewText = with(textView) { setText(R.string.app_name) setTextColor(ContextCompat.getColor(context, R.color.colorPrimary)) setOnClickListener{ Toast.makeText(context, "Hello JAV", Toast.LENGTH_SHORT).show() } // Last statement is return value text } // textViewText = "Miracle of stdLib" }
  • 7. Let, Run fun callApi(callback: ((String) -> Unit)? = null) { val resultString: String? = "" //TODO: Call API and get String result if (resultString != null && callback != null) { callback.invoke(resultString) } } Java Style fun callApi(callback: ((String) -> Unit)? = null) { val resultString: String? = ""//TODO: Call API and get String result resultString?.let { success?.invoke(it) } // or resultString?.run { success?.invoke(this) } } Kotlin Style
  • 8. Let, Run fun sumPair() { val pair: Pair<Int, Int>? = Pair(3, 5) var sum = if (pair != null) pair.first + pair.second else 0 } Java Style fun sumPair() { val pair: Pair<Int, Int>? = Pair(3, 5) val sumRun = pair?.run { first + second } ?: 0 // or val sumLet = pair?.let { it.first + it.second } ?: 0 } Kotlin Style
  • 11. Lazy class FakeFragment : Fragment() { // This approach can not run cuz ... val badPreference = context.getSharedPreferences(...) lateinit var lateInitPreference: SharedPreferences val lazyPreference: SharedPreferences by lazy { context.getSharedPreferences(...) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) lateInitPreference = context.getSharedPreferences(...) lateInitPreference.getString("LATEINIT_PREFERENCE", ":|") lazyPreference.getString("LAZY_PREFERENCE", ":)") } }
  • 12. Observable class HelloObservable { var name by Delegates.observable("time0") { _, old, new -> println("New $new, Old $old") } fun run() { name = "time1" // New time1, Old time0 name = "time2" // New time2, Old time1 name = "time3" // New time3, Old time2 name = "time5" // New time5, Old time3 name = "time6" // New time6, Old time5 } }
  • 13. Vetoable class HelloVetoable { var age by Delegates.vetoable(0) { _, old, new -> println("New $new, Old $old") new < 10 } fun run() { age = 1 // age = 1 age = 2 // age = 2 age = 10 // age = 2 age = 1000 // age = 2 } }
  • 15. Type val list = listOf(1, 2, 3) // [1, 2, 3] val set = setOf("Ant", "Bat", "Cat", "Ant", "Bat") // [Ant, Bat, Cat] val map = mapOf("A" to 1, "B" to 2) // {"A":1, "B":2} val range = 1..5 // [1, 2, 3, 4, 5] val rangeChar = 'A'..'C' // ['A', 'B', 'C'] Immutable val list = mutableListOf("A", "B", "C", "A", "B") // [A, B, C, A, B] list.add("D") // [A, B, C, A, B, D] list.add(0, "Z") // [Z, A, B, C, A, B, D] list.removeAt(1) // [Z, B, C, A, B, D] val set = mutableSetOf("A", "B", "C", "A", "B") // [A, B, C] val map = mutableMapOf("A" to 1, "B" to 2) // {"A":1, "B":2} map.remove("C") // {"A":1, "B":2} Mutable
  • 16. Extension Function val list = listOf(1, 2, 3) list.all { it > 0 } // true list.any { it < 0 } // false list.none { it > 5 } // false list.joinToString("Kotlin") // 1Kotlin2Kotlin3 list.sum() // 6 set.sumBy { it.length } // 9 map.minBy { it.value } // {"A":1} 3 in range // true range.sum() // 15 // Loop for (i in 0..list.size - 1) { list[i] } list.forEach { item -> } list.forEachIndexed { index, item -> } // Convert Type list.toSet() set.toMutableList() map.toList() range.toList()
  • 17. Extension Function (Operator/Infix) val list1 = listOf(1, 2, 3) // [1, 2, 3] val list2 = listOf(3, 4) // [3, 4] val listPlus = list1 + list2 // [1, 2, 3, 3, 4] val listMinus = list1 - list2 // [1, 2] val listContain = 1 in list1 // true val listUnion = list1 union list2 // [1, 2, 3, 4] val listIntersect = list1 intersect list2 // [3] val listSubtract = list1 subtract list2 // [1, 2] val listZip = list1 zip list2 // [(1, 3), (2, 4)] Operator Infix
  • 18. Data Model data class Category(val id: String, val name: String, val subCategoryList: List<Category> = listOf()) data class Product(val id: String, val name: String, val description: String, val price: Double, val category: Category)
  • 19. Search One Item private val categoryList = listOf(Category("1", "sport")) private val productList = listOf( Product("1", "product1", "description1", 100.0, categoryList[0]), Product("2", "product2", "description2", 200.0, categoryList[0]), Product("3", "product3", "description3", 300.0, categoryList[0]), Product("4", "product4", "description4", 400.0, categoryList[0]), Product("5", "product5", "description5", 200.0, categoryList[0]), Product("6", "product6", "description6", 600.0, categoryList[0]) ) fun search_one() { productList.first() // Product 1 productList.first { it.name == "product20" } // Throw NoSuchElementException productList.firstOrNull { it.price == 200.0 } // Product 2 productList.firstOrNull { it.price == 1000.0 } // Null productList.last() // Product 6 productList.lastOrNull { it.price == 200.0 } // Product 5 productList.single() // throw IllegalArgumentException("List has more than one element.") productList.singleOrNull() // Null productList.single { it.price == 600.0 } // Product 6 productList.single { it.price == 200.0 } // throw IllegalArgumentException("Collection contains more than one matching element.") }
  • 20. Advance private val categoryList = listOf( Category("1", "sport1", listOf( Category("4", "sport4"), Category("5", "sport5") )), Category("2", "sport2", listOf( Category("6", "sport6") )), Category("3", "sport3") ) private val productList = listOf( Product("1", "product1", "description1", 100.0, categoryList[0]), Product("2", "product2", "description5", 200.0, categoryList[1]), Product("3", "product3", "description3", 300.0, categoryList[2]), Product("4", "product4", "description4", 400.0, categoryList[1]), Product("5", "product5", "description2", 200.0, categoryList[0]), Product("6", "product6", "description6", 600.0, categoryList[2]) ) fun advance_collection() { productList.filter { it.price > 200.0 } // 3,4,6 productList.filterNot { it.price == 200.0 } // 1,3,4,6 productList.map { it.price * 1.07 } // 107.0, 214.0 ,321.0, 428.0, 214.0, 642.0 vat7% categoryList.flatMap { it.subCategoryList.map { it.name } // [sport4, sport5], [sport6], [] } // [sport4, sport5, sport6] productList.groupBy { it.category } // {cat1:[p1,p5], cat2:[p2,p4], cat3:[p3,p6] productList.sortedBy { it.price } // [p1,p2,p5,p3,p4,p6] productList.sortedByDescending { it.price } //[p6,p4,p3,p5,p2,p1] productList.sortedWith(compareBy(Product::price, Product::description)) // [p1,p5,p2,p3,p4,p6] }