Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Kotlin and why you should love it #2
Search
Roberto Orgiu
July 04, 2017
Technology
130
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Kotlin and why you should love it #2
Slides of the talk we gave in Ennova
Roberto Orgiu
July 04, 2017
More Decks by Roberto Orgiu
See All by Roberto Orgiu
Wellness & Droid
tiwiz
0
140
Behind the curtains
tiwiz
0
94
The Importance of Being Tested
tiwiz
0
450
An Android Dev start to Kotlin MPP
tiwiz
0
210
Fantastic API and where to find them
tiwiz
0
110
Flipping the Koin @ GDG Dev Party
tiwiz
1
83
Flipping the Koin
tiwiz
2
190
Trip into the async world @ NYC Kotlin Meetup
tiwiz
0
130
Trip into the async world
tiwiz
1
160
Other Decks in Technology
See All in Technology
Level Up Your CDK DX: 5 Tools I’ve Been Building
gotok365
2
190
Tab5をRubyで動くパソコンにする
kishima
1
130
推論の観測、できていますか? 〜 Google Cloud Gemini Enterprise Agent Platformで 3つの Gemini モデルを実測して踏んだ、評価の罠 〜
shukob
PRO
0
140
なぜSRE・セキュリティは評価されないのか?守りの組織を事業成長エンジンに変えた実践
cscengineer
PRO
2
2.1k
ブラウザアプリの継続的パフォーマンスモニタリング (序) / Continuous Browser Application Performance Monitoring; Act 1
moznion
0
110
「重なり」は迎える側がつくる ― 人もAIエージェントも歓迎するプロダクトエンジニアリング ―
go0517go
PRO
0
220
AIエージェントの開発・提供におけるセキュリティリスクの論点と対策
flatt_security
1
540
データエンジニアの困りごとをDevinと一緒に解消する
10xinc
2
790
Azure Cost Management の FOCUS コストデータを迷わず読むための“3つの軸”
tetsuyaooooo
0
140
IDperturb: Enhancing Variation in Synthetic Face Generation via Angular Perturbation
sansantech
PRO
0
130
AI活用の現在地、 ちゃんと見えてますか?/XPfest-2026
visional_engineering_and_design
0
130
Amazon S3 Tablesに全部任せてみた結果——コンパクション/スナップショット管理は本当に手放せるか
shigeruoda
0
330
Featured
See All Featured
Balancing Empowerment & Direction
lara
6
1.3k
Six Lessons from altMBA
skipperchong
29
4.5k
Jess Joyce - The Pitfalls of Following Frameworks
techseoconnect
PRO
1
390
実際に使うSQLの書き方 徹底解説 / pgcon21j-tutorial
soudai
PRO
201
75k
HU Berlin: Industrial-Strength Natural Language Processing with spaCy and Prodigy
inesmontani
PRO
0
680
HDC tutorial
michielstock
2
840
The Art of Programming - Codeland 2020
erikaheidi
57
14k
Large-scale JavaScript Application Architecture
addyosmani
515
110k
The Illustrated Children's Guide to Kubernetes
chrisshort
51
53k
How To Speak Unicorn (iThemes Webinar)
marktimemedia
1
570
職位にかかわらず全員がリーダーシップを発揮するチーム作り / Building a team where everyone can demonstrate leadership regardless of position
madoxten
69
65k
SEO for Brand Visibility & Recognition
aleyda
0
4.7k
Transcript
KOTLIN AND WHY YOU SHOULD LOVE IT Part 2
LAMBDAS WITH RECEIVERS The ability to call methods of a
different object in the body of a lambda without any additional qualifiers — Kotlin in Action
with fun alphabet(): String { val result = StringBuilder() for
(letter in 'A'..'Z') { result.append(letter) } result.append("\nNow I know the alphabet!") return result.toString() }
with fun alphabet(): String { val stringBuilder = StringBuilder() return
with(stringBuilder) { for (letter in 'A'..'Z') { this.append(letter) } append("\nNow I know the alphabet!") this.toString() } }
with fun alphabet() = with(StringBuilder()) { for (letter in 'A'..'Z')
{ append(letter) } append("\nNow I know the alphabet!") toString() }
apply fun alphabet() = StringBuilder().apply { for (letter in 'A'..'Z')
{ append(letter) } append("\nNow I know the alphabet!") }.toString()
with VS apply Declaration Return type with Function value of
the lambda apply Extension method this
with VS apply inline fun <T, R> with(receiver: T, block:
T.() -> R): R = receiver.block() inline fun <T> T.apply(block: T.() -> Unit): T { block() return this }
let VS run inline fun <T, R> T.run(block: T.() ->
R): R = block() inline fun <T, R> T.let(block: (T) -> R): R = block(this)
DESTRUCTURING DECLARATION val mickey = Person("Mickey", "Mouse") val (name, lastName)
= mickey
DESTRUCTURING DECLARATION val mickey = Person("Mickey", "Mouse") val (name, lastName)
= mickey MEANS val name = mickey.component1() val lastName = mickey.component2()
LOCAL FUNCTIONS Functions can be nested inside a containing function
And they have access to all parameters and variables of the enclosing function
LOCAL FUNCTIONS fun containing(a : Int) { fun nested() {
return a + 2 } val b = nested() }
SEALED CLASSES sealed class Expr data class Const(val number: Double)
: Expr() data class Sum(val e1: Expr, val e2: Expr) : Expr() object NotANumber : Expr()
SEALED CLASSES fun eval(expr: Expr): Double = when(expr) { is
Const -> expr.number is Sum -> eval(expr.e1) + eval(expr.e2) NotANumber -> Double.NaN }
SINGLETON AKA object DECLARATIONS
object DataProviderManager { fun register(provider: Provider) { // ... }
}
THIS IS NOT THE ONLY USE OF object
object EXPRESSIONS textView.addTextChangedListener(object : TextWatcher{ override fun afterTextChanged(...) {} override
fun beforeTextChanged(...) {} override fun onTextChanged(...) {} })
COMPANION object class MyClass { companion object Factory { fun
create(): MyClass = MyClass() } } val instance = MyClass.create()
COMPANION object class MyClass { companion object { } }
val x = MyClass.Companion
object init > object declarations are initialized lazily, when accessed
for the first time > object expressions are executed (and initialized) immediately, where they are used > a companion object is initialized when the corresponding class is loaded (resolved), matching the semantics of a Java static initializer
DELEGATION
interface Base { fun print() } class BaseImpl(val x: Int)
: Base { override fun print() { print(x) } }
val b = BaseImpl(10)
class Derived(b: Base) : Base by b
val b = BaseImpl(10) Derived(b).print() This prints 10
class Derived(b: Base) : Base by b { override fun
print() { print("abc") } }
val b = BaseImpl(10) Derived(b).print() This prints abc
STANDARD DELEGATES
lazy - THIS... val lazyValue: String by lazy { println("computed!")
"Hello" } println(lazyValue) println(lazyValue)
lazy - ... WILL PRINT computed! Hello Hello
Delegates.observable() - THIS ... class User { var name: String
by Delegates.observable("<no name>") { prop, old, new -> println("$old -> $new") } } fun main(args: Array<String>) { val user = User() user.name = "first" user.name = "second" }
Delegates.observable() - ... WILL PRINT <no name> -> first first
-> second
THE HANDLER WILL BE CALLED AFTER THE VALUE HAS BEEN
SET
Delegates.vetoable()
map DELEGATE class User(map: Map<String, Any?>) { val name: String
by map val age: Int by map } val user = User(mapOf( "name" to "John Doe", "age" to 25 ))
COLLECTIONS: MUTABLE VS IMMUTABLE val list = listOf(1, 2, 3)
//immutable list of ints val list = mutableListOf(1, 2, 3) //mutable list of ints
COLLECTIONS: MUTABLE VS IMMUTABLE > Mutable: you can insert, update
and remove > Default: you can only query (contains, get, indexOf...) > MutableList / List > MutableSet / Set > MutableMap / Map
COLLECTIONS: IMMUTABILITY val list = listOf(1, 2, 3) val doubles
= list.map { it * 2 } val pairs = list.filter { it % 2 == 0 } > doubles is a completely new list > The original list is never touched
COLLECTIONS: OPERATIONS > filter > map > any, none, all
> firstOrNull
More info at https://kotlinlang.org/docs/reference/ delegated-properties.html
SLIDES bit.ly/ennova
THANKS!