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
110
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
100
Behind the curtains
tiwiz
0
47
The Importance of Being Tested
tiwiz
0
390
An Android Dev start to Kotlin MPP
tiwiz
0
150
Fantastic API and where to find them
tiwiz
0
59
Flipping the Koin @ GDG Dev Party
tiwiz
1
47
Flipping the Koin
tiwiz
2
140
Trip into the async world @ NYC Kotlin Meetup
tiwiz
0
90
Trip into the async world
tiwiz
1
110
Other Decks in Technology
See All in Technology
React開発にStorybookとCopilotを導入して、爆速でUIを編集・確認する方法
yu_kod
1
110
生成AI活用の組織格差を解消する 〜ビジネス職のCursor導入が開発効率に与えた好循環〜 / Closing the Organizational Gap in AI Adoption
upamune
6
4.7k
整頓のジレンマとの戦い〜Tidy First?で振り返る事業とキャリアの歩み〜/Fighting the tidiness dilemma〜Business and Career Milestones Reflected on in Tidy First?〜
bitkey
1
6.7k
Zephyr RTOSを使った開発コンペに参加した件
iotengineer22
1
170
無意味な開発生産性の議論から抜け出すための予兆検知とお金とAI
i35_267
2
6.2k
AI専用のリンターを作る #yumemi_patch
bengo4com
5
2.4k
PO初心者が考えた ”POらしさ”
nb_rady
0
120
製造業からパッケージ製品まで、あらゆる領域をカバー!生成AIを利用したテストシナリオ生成 / 20250627 Suguru Ishii
shift_evolve
PRO
1
160
モバイル界のMCPを考える
naoto33
0
380
タイミーのデータモデリング事例と今後のチャレンジ
ttccddtoki
6
2.1k
Lazy application authentication with Tailscale
bluehatbrit
0
140
さくらのIaaS基盤のモニタリングとOpenTelemetry/OSC Hokkaido 2025
fujiwara3
2
290
Featured
See All Featured
Put a Button on it: Removing Barriers to Going Fast.
kastner
60
3.9k
A Tale of Four Properties
chriscoyier
160
23k
What’s in a name? Adding method to the madness
productmarketing
PRO
23
3.5k
Optimising Largest Contentful Paint
csswizardry
37
3.3k
Bootstrapping a Software Product
garrettdimon
PRO
307
110k
Exploring the Power of Turbo Streams & Action Cable | RailsConf2023
kevinliebholz
34
5.9k
Optimizing for Happiness
mojombo
379
70k
YesSQL, Process and Tooling at Scale
rocio
173
14k
Save Time (by Creating Custom Rails Generators)
garrettdimon
PRO
31
1.3k
How to Create Impact in a Changing Tech Landscape [PerfNow 2023]
tammyeverts
53
2.8k
Building Flexible Design Systems
yeseniaperezcruz
328
39k
10 Git Anti Patterns You Should be Aware of
lemiorhan
PRO
657
60k
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!