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
0
94
Kotlin and why you should love it #2
Slides of the talk we gave in Ennova
Roberto Orgiu
July 04, 2017
Tweet
Share
More Decks by Roberto Orgiu
See All by Roberto Orgiu
Wellness & Droid
tiwiz
0
75
Behind the curtains
tiwiz
0
24
The Importance of Being Tested
tiwiz
0
280
An Android Dev start to Kotlin MPP
tiwiz
0
100
Fantastic API and where to find them
tiwiz
0
34
Flipping the Koin @ GDG Dev Party
tiwiz
1
33
Flipping the Koin
tiwiz
2
110
Trip into the async world @ NYC Kotlin Meetup
tiwiz
0
61
Trip into the async world
tiwiz
1
84
Other Decks in Technology
See All in Technology
Amplify Gen2を 拡張してみよう JAWS-UG北陸新幹線 ( 福井開催 ) 2024-04-06/Let's extend Amplify Gen2
fossamagna
0
280
Databricks:『生成AI World Cup』のご案内
databricksjapan
2
140
プロトタイピングによる不確実性の低減 / Reducing Uncertainty through Prototyping
ohbarye
3
210
"好き"との生活/Regularly update profile with GitHub Actions
judeeeee
0
150
なぜ NOT A HOTEL が Web3 に取り組むのか - NOT A HOTEL TECH TALK
ynunokawa
0
160
**強い**エンジニアのなり方 - フィードバックサイクルを勝ち取る / grow one day each day
soudai
60
17k
4年前、あるじゃん老害エンジニアLT合戦に登壇、米国西海岸コンピュータ歴史博物館体験記の続編
toshi_atsumi
0
190
SREとその組織類型
tatsuo48
8
1.5k
ここが嬉しいABAC ここが辛いよABAC #再解説+補足編
masahirokawahara
0
200
コードを書く隙間を見つけて生きていく技術/Findy 思考の現在地
fujiwara3
24
4.9k
Garoon 開発チーム / Garoon development team
cybozuinsideout
PRO
2
2.9k
Hands-on / Kaname Frusawa / Cloud Compare Users Meetup 2024 at University of Tokyo on April 17
paraworld
2
470
Featured
See All Featured
Designing for Performance
lara
602
67k
In The Pink: A Labor of Love
frogandcode
138
21k
How to Ace a Technical Interview
jacobian
272
22k
Designing Experiences People Love
moore
136
23k
Rebuilding a faster, lazier Slack
samanthasiow
72
8.2k
A better future with KSS
kneath
231
16k
Unsuck your backbone
ammeep
662
57k
CSS Pre-Processors: Stylus, Less & Sass
bermonpainter
352
28k
A Modern Web Designer's Workflow
chriscoyier
689
190k
Responsive Adventures: Dirty Tricks From The Dark Corners of Front-End
smashingmag
243
20k
Designing on Purpose - Digital PM Summit 2013
jponch
110
6.4k
Principles of Awesome APIs and How to Build Them.
keavy
120
16k
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!