SlideShare une entreprise Scribd logo
1  sur  57
Kotlin StandardLib
let, with, apply, run, also…
LazySoul
우명인
Standard
• let
• with
• apply
• run
• also
• takeIf, takeUnless
• use
• repeat
Standard
data class Person(var name: String = "myeongin",
var age: Int = 18)
val person = Person()
let
inline fun <T, R> T.let(block: (T) -> R)
: R = block(this)
let
val name = person.let { it.name }
inline fun <T, R> T.let(block: (T) -> R)
: R = block(this)
let
val name = person.let { it.name }
println(name) // myeongin
inline fun <T, R> T.let(block: (T) -> R)
: R = block(this)
let
val person: Person? = Person()
inline fun <T, R> T.let(block: (T) -> R)
: R = block(this)
let
val person: Person? = Person()
val name = person?.let { it.name }
inline fun <T, R> T.let(block: (T) -> R)
: R = block(this)
let
val person: Person? = Person()
val name = person?.let { it.name }
println(name) // myeongin
inline fun <T, R> T.let(block: (T) -> R)
: R = block(this)
let
val person: Person? = null
inline fun <T, R> T.let(block: (T) -> R)
: R = block(this)
let
val person: Person? = null
val name = person.let { it.name } // Error
inline fun <T, R> T.let(block: (T) -> R)
: R = block(this)
let
val person: Person? = null
val name = person?.let { it.name }
inline fun <T, R> T.let(block: (T) -> R)
: R = block(this)
let
val person: Person? = null
val name = person?.let { it.name }
println(name) // null
inline fun <T, R> T.let(block: (T) -> R)
: R = block(this)
let
val person: Person? = null
val name = person?.let { it.name } ?: "Lezhin"
inline fun <T, R> T.let(block: (T) -> R)
: R = block(this)
let
val person: Person? = null
val name = person?.let { it.name } ?: "Lezhin"
println(name) // Lezhin
inline fun <T, R> T.let(block: (T) -> R)
: R = block(this)
let
fun sendEmail(email: String) {
TODO()
}
var email: String? = null
email?.let { sendEmail(it) }
inline fun <T, R> T.let(block: (T) -> R)
: R = block(this)
let
• type T(자신)을 block으로 감쌉니다.
• block 안에서 자기자신에게 접근 할때는 it을 사용합니다.
• 표현식으로 사용한다면 반환 값 R은 괄호 제일 마지막 라인의 값이 됩니다.
• ?.을 사용해 null check를 할 수 있습니다.
• null일 경우에 ?. 을 사용하면 null 을 반환합니다.
inline fun <T, R> T.let(block: (T) -> R)
: R = block(this)
with
inline fun <T, R> with(receiver: T, block: T.() -> R)
: R = receiver.block()
with
inline fun <T, R> with(receiver: T, block: T.() -> R)
: R = receiver.block()
with(person) {
name = "ari"
}
with
inline fun <T, R> with(receiver: T, block: T.() -> R)
: R = receiver.block()
with(person) {
name = "ari"
}
println(person) // Person(name=ari, age=18)
with
inline fun <T, R> with(receiver: T, block: T.() -> R)
: R = receiver.block()
recyclerView.apply {
layoutManager = LinearLayoutManager(context, LinearLayoutManager
adapter = this@Activity.adapter
addItemDecoration(Adapter.ContentDecoration(context))
}
with
inline fun <T, R> with(receiver: T, block: T.() -> R)
: R = receiver.block()
val ari = with(person) {
name = "ari"
}
println(ari) // Unit
with
inline fun <T, R> with(receiver: T, block: T.() -> R)
: R = receiver.block()
• T를 with의 인자로 전달합니다.
• block 안에서는 마치 object 내부 처럼 property를 자유롭게 접근합니다.
• 표현식으로 사용한다면 반환 값 R은 괄호 제일 마지막 라인의 값이 됩니다.
• 특정 instance의 내부 값들을 수정 하거나 조합할때 사용하면 좋습니다.
apply
inline fun <T> T.apply(f: T.() -> Unit)
: T { f(); return this }
apply
inline fun <T> T.apply(f: T.() -> Unit)
: T { f(); return this }
val person = Person().apply {
name = "ari"
age = 24
}
apply
inline fun <T> T.apply(f: T.() -> Unit)
: T { f(); return this }
val person = Person().apply {
name = "ari"
age = 24
}
println(person) //Person(name=ari, age=24)
apply
inline fun <T> T.apply(f: T.() -> Unit)
: T { f(); return this }
AlertDialog.Builder(this).apply {
setTitle(getString(R.string.title))
setMessage(getString(R.string.message))
setPositiveButton(getString(R.string.ok),
{ dlg, _ -> dlg.dismiss() })
create()
show()
}
apply
inline fun <T> T.apply(f: T.() -> Unit)
: T { f(); return this }
• type.apply { .. } 을 사용합니다.
• type T를 입력받아 { .. } 안을 수행하고 자기 자신을 반환합니다.
• 생성과 동시에 추가적인 작업을 해줘야 할 때 유용합니다.
run
inline fun <R> run(block: () -> R): R = block()
inline fun <T, R> T.run(block: T.() -> R)
: R = block()
run
val name = person.run { name }
inline fun <R> run(block: () -> R): R = block()
inline fun <T, R> T.run(block: T.() -> R)
: R = block()
run
val name = person.run { name }
println(name) // myeongin
inline fun <R> run(block: () -> R): R = block()
inline fun <T, R> T.run(block: T.() -> R)
: R = block()
run
run {
sendEmail(name)
}
inline fun <R> run(block: () -> R): R = block()
inline fun <T, R> T.run(block: T.() -> R)
: R = block()
run
• let과 거의 유사합니다. 하지만 let은 T를 인자로 받지만 (T) run은 T.() T의 자신을 블럭 으로 지
정합니다.(this)
• 별도로 함수를 만들지 않고 block 을 통해 함수 구문을 만들고 실행 할수 있습니다.
• 역시나 마지막줄의 값을 반환합니다.
inline fun <R> run(block: () -> R): R = block()
inline fun <T, R> T.run(block: T.() -> R)
: R = block()
also
inline fun <T> T.also(block: (T) -> Unit)
: T { block(this); return this }
also
inline fun <T> T.also(block: (T) -> Unit)
: T { block(this); return this }
person.also {
it.name = "ari"
}
println(person) //Person(name=ari, age=18)
also
inline fun <T> T.also(block: (T) -> Unit)
: T { block(this); return this }
• let과 거의 유사합니다. let은 R을 반환 하는 반면 also는 자기자신 T를 반환합니다.
• 마지막줄의 값과 상관없이 자기 자신을 반환합니다.
let, run, with, also, apply
takeIf
inline fun <T> T.takeIf(predicate: (T) -> Boolean)
: T? = if (predicate(this)) this else null
takeIf
inline fun <T> T.takeIf(predicate: (T) -> Boolean)
: T? = if (predicate(this)) this else null
val ari = person.takeIf { it.name == "ari" }
takeIf
inline fun <T> T.takeIf(predicate: (T) -> Boolean)
: T? = if (predicate(this)) this else null
val ari = person.takeIf { it.name == "ari" }
println(ari) // null
takeIf
inline fun <T> T.takeIf(predicate: (T) -> Boolean)
: T? = if (predicate(this)) this else null
val ari = person.takeIf { it.name == "ari" }
println(ari) // null
val myeongin = person.takeIf { it.name == "myeongin" }
takeIf
inline fun <T> T.takeIf(predicate: (T) -> Boolean)
: T? = if (predicate(this)) this else null
val ari = person.takeIf { it.name == "ari" }
println(ari) // null
val myeongin = person.takeIf { it.name == "myeongin" }
println(myeongin) // Person(name=myeongin, age=18)
takeIf
inline fun <T> T.takeIf(predicate: (T) -> Boolean)
: T? = if (predicate(this)) this else null
val ari = person.takeIf { it.name == "ari" }
println(ari) // null
val myeongin = person.takeIf { it.name == "myeongin" }
println(myeongin) // Person(name=myeongin, age=18)
val default = person.takeIf { it.name == "ari" } ?: Person("ari", 24)
takeIf
inline fun <T> T.takeIf(predicate: (T) -> Boolean)
: T? = if (predicate(this)) this else null
val ari = person.takeIf { it.name == "ari" }
println(ari) // null
val myeongin = person.takeIf { it.name == "myeongin" }
println(myeongin) // Person(name=myeongin, age=18)
val default = person.takeIf { it.name == "ari" } ?: Person("ari", 24)
println(default) // Person(name=ari, age=24)
takeUnless
inline fun <T> T.takeUnless(predicate: (T) -> Boolean)
: T? = if (!predicate(this)) this else null
takeUnless
inline fun <T> T.takeUnless(predicate: (T) -> Boolean)
: T? = if (!predicate(this)) this else null
val ari = person.takeUnless { it.name == "ari" }
takeUnless
inline fun <T> T.takeUnless(predicate: (T) -> Boolean)
: T? = if (!predicate(this)) this else null
val ari = person.takeUnless { it.name == "ari" }
println(ari) // Person(name=myeongin, age=18)
takeUnless
inline fun <T> T.takeUnless(predicate: (T) -> Boolean)
: T? = if (!predicate(this)) this else null
val ari = person.takeUnless { it.name == "ari" }
println(ari) // Person(name=myeongin, age=18)
val myeongin = person.takeUnless {
it.name == "myeongin" }
takeUnless
inline fun <T> T.takeUnless(predicate: (T) -> Boolean)
: T? = if (!predicate(this)) this else null
val ari = person.takeUnless { it.name == "ari" }
println(ari) // Person(name=myeongin, age=18)
val myeongin = person.takeUnless {
it.name == "myeongin" }
println(myeongin) // null
takeUnless
inline fun <T> T.takeUnless(predicate: (T) -> Boolean)
: T? = if (!predicate(this)) this else null
val ari = person.takeUnless { it.name == "ari" }
println(ari) // Person(name=myeongin, age=18)
val myeongin = person.takeUnless {
it.name == "myeongin" }
println(myeongin) // null
val default = person.takeUnless { it.name == "ari" }
?: Person("ari", 24)
takeUnless
inline fun <T> T.takeUnless(predicate: (T) -> Boolean)
: T? = if (!predicate(this)) this else null
val ari = person.takeUnless { it.name == "ari" }
println(ari) // Person(name=myeongin, age=18)
val myeongin = person.takeUnless {
it.name == "myeongin" }
println(myeongin) // null
val default = person.takeUnless { it.name == "ari" }
?: Person("ari", 24)
println(default) // Person(name=myeongin, age=18)
use
// Java 1.6
Properties property = new Properties();
FileInputStream stream = new FileInputStream("config.properties");
try {
property.load(steam);
} finally {
stream.close();
}
// Java 1.7
Properties property = new Properties();
try (FileInputStream stream = new FileInputStream("config.properties")) {
property.load(stream);
} // FileInputStream는 자동으로 close됨
use
public inline fun <T : Closeable?, R> T.use(block: (T) -> R): R {
var closed = false
try {
return block(this)
} catch (e: Exception) {
closed = true
try {
this?.close()
} catch (closeException: Exception) {
}
throw e
} finally {
if (!closed) {
this?.close()
}
}
}
use
public inline fun <T : Closeable?, R> T.use(block: (T) -> R): R {
var closed = false
try {
return block(this)
} catch (e: Exception) {
closed = true
try {
this?.close()
} catch (closeException: Exception) {
}
throw e
} finally {
if (!closed) {
this?.close()
}
}
}
val property = Properties()
FileInputStream("config.properties").use {
property.load(it)
} // FileInputStream이 자동으로 close됨.
repeat
inline fun repeat(times: Int, action: (Int) -> Unit) {
for (index in 0..times - 1) {
action(index)
}
}
repeat
inline fun repeat(times: Int, action: (Int) -> Unit) {
for (index in 0..times - 1) {
action(index)
}
}
repeat(4, { println("Hello, World") })
repeat
inline fun repeat(times: Int, action: (Int) -> Unit) {
for (index in 0..times - 1) {
action(index)
}
}
repeat(4, { println("Hello, World") })
// Hello, World
// Hello, World
// Hello, World
// Hello, World

Contenu connexe

Tendances

Java 8 Puzzlers [as presented at OSCON 2016]
Java 8 Puzzlers [as presented at  OSCON 2016]Java 8 Puzzlers [as presented at  OSCON 2016]
Java 8 Puzzlers [as presented at OSCON 2016]Baruch Sadogursky
 
Taming Asynchronous Transforms with Interstellar
Taming Asynchronous Transforms with InterstellarTaming Asynchronous Transforms with Interstellar
Taming Asynchronous Transforms with InterstellarJens Ravens
 
Stanfy MadCode Meetup #9: Functional Programming 101 with Swift
Stanfy MadCode Meetup #9: Functional Programming 101 with SwiftStanfy MadCode Meetup #9: Functional Programming 101 with Swift
Stanfy MadCode Meetup #9: Functional Programming 101 with SwiftStanfy
 
Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)stasimus
 
Go ahead, make my day
Go ahead, make my dayGo ahead, make my day
Go ahead, make my dayTor Ivry
 
Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Baruch Sadogursky
 
From java to kotlin beyond alt+shift+cmd+k
From java to kotlin beyond alt+shift+cmd+kFrom java to kotlin beyond alt+shift+cmd+k
From java to kotlin beyond alt+shift+cmd+kFabio Collini
 
Python 2.5 reference card (2009)
Python 2.5 reference card (2009)Python 2.5 reference card (2009)
Python 2.5 reference card (2009)gekiaruj
 
Python3 cheatsheet
Python3 cheatsheetPython3 cheatsheet
Python3 cheatsheetGil Cohen
 
Beginning Haskell, Dive In, Its Not That Scary!
Beginning Haskell, Dive In, Its Not That Scary!Beginning Haskell, Dive In, Its Not That Scary!
Beginning Haskell, Dive In, Its Not That Scary!priort
 
Implementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 reduxImplementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 reduxEleanor McHugh
 
The secrets of inverse brogramming
The secrets of inverse brogrammingThe secrets of inverse brogramming
The secrets of inverse brogrammingRichie Cotton
 
Predictably
PredictablyPredictably
Predictablyztellman
 
関数潮流(Function Tendency)
関数潮流(Function Tendency)関数潮流(Function Tendency)
関数潮流(Function Tendency)riue
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that LetterKevlin Henney
 

Tendances (20)

Java 8 Puzzlers [as presented at OSCON 2016]
Java 8 Puzzlers [as presented at  OSCON 2016]Java 8 Puzzlers [as presented at  OSCON 2016]
Java 8 Puzzlers [as presented at OSCON 2016]
 
Taming Asynchronous Transforms with Interstellar
Taming Asynchronous Transforms with InterstellarTaming Asynchronous Transforms with Interstellar
Taming Asynchronous Transforms with Interstellar
 
Stanfy MadCode Meetup #9: Functional Programming 101 with Swift
Stanfy MadCode Meetup #9: Functional Programming 101 with SwiftStanfy MadCode Meetup #9: Functional Programming 101 with Swift
Stanfy MadCode Meetup #9: Functional Programming 101 with Swift
 
Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)
 
Go ahead, make my day
Go ahead, make my dayGo ahead, make my day
Go ahead, make my day
 
Benefits of Kotlin
Benefits of KotlinBenefits of Kotlin
Benefits of Kotlin
 
Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014
 
From java to kotlin beyond alt+shift+cmd+k
From java to kotlin beyond alt+shift+cmd+kFrom java to kotlin beyond alt+shift+cmd+k
From java to kotlin beyond alt+shift+cmd+k
 
Python 2.5 reference card (2009)
Python 2.5 reference card (2009)Python 2.5 reference card (2009)
Python 2.5 reference card (2009)
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
ScalaBlitz
ScalaBlitzScalaBlitz
ScalaBlitz
 
Python3 cheatsheet
Python3 cheatsheetPython3 cheatsheet
Python3 cheatsheet
 
Beginning Haskell, Dive In, Its Not That Scary!
Beginning Haskell, Dive In, Its Not That Scary!Beginning Haskell, Dive In, Its Not That Scary!
Beginning Haskell, Dive In, Its Not That Scary!
 
Implementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 reduxImplementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 redux
 
The secrets of inverse brogramming
The secrets of inverse brogrammingThe secrets of inverse brogramming
The secrets of inverse brogramming
 
ScalaMeter 2014
ScalaMeter 2014ScalaMeter 2014
ScalaMeter 2014
 
Predictably
PredictablyPredictably
Predictably
 
関数潮流(Function Tendency)
関数潮流(Function Tendency)関数潮流(Function Tendency)
関数潮流(Function Tendency)
 
Python_ 3 CheatSheet
Python_ 3 CheatSheetPython_ 3 CheatSheet
Python_ 3 CheatSheet
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that Letter
 

Similaire à Kotlin standard

Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlinintelliyole
 
The Ring programming language version 1.5.3 book - Part 36 of 184
The Ring programming language version 1.5.3 book - Part 36 of 184The Ring programming language version 1.5.3 book - Part 36 of 184
The Ring programming language version 1.5.3 book - Part 36 of 184Mahmoud Samir Fayed
 
The Ring programming language version 1.3 book - Part 27 of 88
The Ring programming language version 1.3 book - Part 27 of 88The Ring programming language version 1.3 book - Part 27 of 88
The Ring programming language version 1.3 book - Part 27 of 88Mahmoud Samir Fayed
 
かとうの Kotlin 講座 こってり版
かとうの Kotlin 講座 こってり版かとうの Kotlin 講座 こってり版
かとうの Kotlin 講座 こってり版Yutaka Kato
 
The Ring programming language version 1.5.2 book - Part 35 of 181
The Ring programming language version 1.5.2 book - Part 35 of 181The Ring programming language version 1.5.2 book - Part 35 of 181
The Ring programming language version 1.5.2 book - Part 35 of 181Mahmoud Samir Fayed
 
oop presentation note
oop presentation note oop presentation note
oop presentation note Atit Patumvan
 
Scala - fra newbie til ninja på en time
Scala - fra newbie til ninja på en timeScala - fra newbie til ninja på en time
Scala - fra newbie til ninja på en timekarianneberg
 
Что нам готовит грядущий C#7?
Что нам готовит грядущий C#7?Что нам готовит грядущий C#7?
Что нам готовит грядущий C#7?Andrey Akinshin
 
The Ring programming language version 1.6 book - Part 26 of 189
The Ring programming language version 1.6 book - Part 26 of 189The Ring programming language version 1.6 book - Part 26 of 189
The Ring programming language version 1.6 book - Part 26 of 189Mahmoud Samir Fayed
 
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기Suyeol Jeon
 
Mastering Kotlin Standard Library
Mastering Kotlin Standard LibraryMastering Kotlin Standard Library
Mastering Kotlin Standard LibraryNelson Glauber Leal
 
I need to fill-in TODOs in .cpp file and in .h file Could some.pdf
I need to fill-in TODOs in .cpp file and in .h file Could some.pdfI need to fill-in TODOs in .cpp file and in .h file Could some.pdf
I need to fill-in TODOs in .cpp file and in .h file Could some.pdfforladies
 
Kotlin for Android Developers
Kotlin for Android DevelopersKotlin for Android Developers
Kotlin for Android DevelopersHassan Abid
 
The Ring programming language version 1.7 book - Part 26 of 196
The Ring programming language version 1.7 book - Part 26 of 196The Ring programming language version 1.7 book - Part 26 of 196
The Ring programming language version 1.7 book - Part 26 of 196Mahmoud Samir Fayed
 
Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3Kirill Rozov
 
Revision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.docRevision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.docSrikrishnaVundavalli
 
The Ring programming language version 1.8 book - Part 29 of 202
The Ring programming language version 1.8 book - Part 29 of 202The Ring programming language version 1.8 book - Part 29 of 202
The Ring programming language version 1.8 book - Part 29 of 202Mahmoud Samir Fayed
 

Similaire à Kotlin standard (20)

Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlin
 
The Ring programming language version 1.5.3 book - Part 36 of 184
The Ring programming language version 1.5.3 book - Part 36 of 184The Ring programming language version 1.5.3 book - Part 36 of 184
The Ring programming language version 1.5.3 book - Part 36 of 184
 
The Ring programming language version 1.3 book - Part 27 of 88
The Ring programming language version 1.3 book - Part 27 of 88The Ring programming language version 1.3 book - Part 27 of 88
The Ring programming language version 1.3 book - Part 27 of 88
 
かとうの Kotlin 講座 こってり版
かとうの Kotlin 講座 こってり版かとうの Kotlin 講座 こってり版
かとうの Kotlin 講座 こってり版
 
The Ring programming language version 1.5.2 book - Part 35 of 181
The Ring programming language version 1.5.2 book - Part 35 of 181The Ring programming language version 1.5.2 book - Part 35 of 181
The Ring programming language version 1.5.2 book - Part 35 of 181
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Scala 2 + 2 > 4
Scala 2 + 2 > 4Scala 2 + 2 > 4
Scala 2 + 2 > 4
 
oop presentation note
oop presentation note oop presentation note
oop presentation note
 
Kotlin
KotlinKotlin
Kotlin
 
Scala - fra newbie til ninja på en time
Scala - fra newbie til ninja på en timeScala - fra newbie til ninja på en time
Scala - fra newbie til ninja på en time
 
Что нам готовит грядущий C#7?
Что нам готовит грядущий C#7?Что нам готовит грядущий C#7?
Что нам готовит грядущий C#7?
 
The Ring programming language version 1.6 book - Part 26 of 189
The Ring programming language version 1.6 book - Part 26 of 189The Ring programming language version 1.6 book - Part 26 of 189
The Ring programming language version 1.6 book - Part 26 of 189
 
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
 
Mastering Kotlin Standard Library
Mastering Kotlin Standard LibraryMastering Kotlin Standard Library
Mastering Kotlin Standard Library
 
I need to fill-in TODOs in .cpp file and in .h file Could some.pdf
I need to fill-in TODOs in .cpp file and in .h file Could some.pdfI need to fill-in TODOs in .cpp file and in .h file Could some.pdf
I need to fill-in TODOs in .cpp file and in .h file Could some.pdf
 
Kotlin for Android Developers
Kotlin for Android DevelopersKotlin for Android Developers
Kotlin for Android Developers
 
The Ring programming language version 1.7 book - Part 26 of 196
The Ring programming language version 1.7 book - Part 26 of 196The Ring programming language version 1.7 book - Part 26 of 196
The Ring programming language version 1.7 book - Part 26 of 196
 
Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3
 
Revision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.docRevision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.doc
 
The Ring programming language version 1.8 book - Part 29 of 202
The Ring programming language version 1.8 book - Part 29 of 202The Ring programming language version 1.8 book - Part 29 of 202
The Ring programming language version 1.8 book - Part 29 of 202
 

Plus de Myeongin Woo

DroidKnight 2018 State machine by Selaed class
DroidKnight 2018 State machine by Selaed classDroidKnight 2018 State machine by Selaed class
DroidKnight 2018 State machine by Selaed classMyeongin Woo
 
Lezhin kotlin jetbrain
Lezhin kotlin jetbrainLezhin kotlin jetbrain
Lezhin kotlin jetbrainMyeongin Woo
 
토이 프로젝트를 하자.Pptx
토이 프로젝트를 하자.Pptx토이 프로젝트를 하자.Pptx
토이 프로젝트를 하자.PptxMyeongin Woo
 

Plus de Myeongin Woo (8)

Goodbye null
Goodbye nullGoodbye null
Goodbye null
 
Fp basic-kotlin
Fp basic-kotlinFp basic-kotlin
Fp basic-kotlin
 
DroidKnight 2018 State machine by Selaed class
DroidKnight 2018 State machine by Selaed classDroidKnight 2018 State machine by Selaed class
DroidKnight 2018 State machine by Selaed class
 
Lezhin kotlin jetbrain
Lezhin kotlin jetbrainLezhin kotlin jetbrain
Lezhin kotlin jetbrain
 
Kotlin expression
Kotlin expressionKotlin expression
Kotlin expression
 
Kotlin with fp
Kotlin with fpKotlin with fp
Kotlin with fp
 
토이 프로젝트를 하자.Pptx
토이 프로젝트를 하자.Pptx토이 프로젝트를 하자.Pptx
토이 프로젝트를 하자.Pptx
 
Kotlin.md
Kotlin.mdKotlin.md
Kotlin.md
 

Dernier

HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 

Dernier (20)

HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 

Kotlin standard

  • 1. Kotlin StandardLib let, with, apply, run, also… LazySoul 우명인
  • 2. Standard • let • with • apply • run • also • takeIf, takeUnless • use • repeat
  • 3. Standard data class Person(var name: String = "myeongin", var age: Int = 18) val person = Person()
  • 4. let inline fun <T, R> T.let(block: (T) -> R) : R = block(this)
  • 5. let val name = person.let { it.name } inline fun <T, R> T.let(block: (T) -> R) : R = block(this)
  • 6. let val name = person.let { it.name } println(name) // myeongin inline fun <T, R> T.let(block: (T) -> R) : R = block(this)
  • 7. let val person: Person? = Person() inline fun <T, R> T.let(block: (T) -> R) : R = block(this)
  • 8. let val person: Person? = Person() val name = person?.let { it.name } inline fun <T, R> T.let(block: (T) -> R) : R = block(this)
  • 9. let val person: Person? = Person() val name = person?.let { it.name } println(name) // myeongin inline fun <T, R> T.let(block: (T) -> R) : R = block(this)
  • 10. let val person: Person? = null inline fun <T, R> T.let(block: (T) -> R) : R = block(this)
  • 11. let val person: Person? = null val name = person.let { it.name } // Error inline fun <T, R> T.let(block: (T) -> R) : R = block(this)
  • 12. let val person: Person? = null val name = person?.let { it.name } inline fun <T, R> T.let(block: (T) -> R) : R = block(this)
  • 13. let val person: Person? = null val name = person?.let { it.name } println(name) // null inline fun <T, R> T.let(block: (T) -> R) : R = block(this)
  • 14. let val person: Person? = null val name = person?.let { it.name } ?: "Lezhin" inline fun <T, R> T.let(block: (T) -> R) : R = block(this)
  • 15. let val person: Person? = null val name = person?.let { it.name } ?: "Lezhin" println(name) // Lezhin inline fun <T, R> T.let(block: (T) -> R) : R = block(this)
  • 16. let fun sendEmail(email: String) { TODO() } var email: String? = null email?.let { sendEmail(it) } inline fun <T, R> T.let(block: (T) -> R) : R = block(this)
  • 17. let • type T(자신)을 block으로 감쌉니다. • block 안에서 자기자신에게 접근 할때는 it을 사용합니다. • 표현식으로 사용한다면 반환 값 R은 괄호 제일 마지막 라인의 값이 됩니다. • ?.을 사용해 null check를 할 수 있습니다. • null일 경우에 ?. 을 사용하면 null 을 반환합니다. inline fun <T, R> T.let(block: (T) -> R) : R = block(this)
  • 18. with inline fun <T, R> with(receiver: T, block: T.() -> R) : R = receiver.block()
  • 19. with inline fun <T, R> with(receiver: T, block: T.() -> R) : R = receiver.block() with(person) { name = "ari" }
  • 20. with inline fun <T, R> with(receiver: T, block: T.() -> R) : R = receiver.block() with(person) { name = "ari" } println(person) // Person(name=ari, age=18)
  • 21. with inline fun <T, R> with(receiver: T, block: T.() -> R) : R = receiver.block() recyclerView.apply { layoutManager = LinearLayoutManager(context, LinearLayoutManager adapter = this@Activity.adapter addItemDecoration(Adapter.ContentDecoration(context)) }
  • 22. with inline fun <T, R> with(receiver: T, block: T.() -> R) : R = receiver.block() val ari = with(person) { name = "ari" } println(ari) // Unit
  • 23. with inline fun <T, R> with(receiver: T, block: T.() -> R) : R = receiver.block() • T를 with의 인자로 전달합니다. • block 안에서는 마치 object 내부 처럼 property를 자유롭게 접근합니다. • 표현식으로 사용한다면 반환 값 R은 괄호 제일 마지막 라인의 값이 됩니다. • 특정 instance의 내부 값들을 수정 하거나 조합할때 사용하면 좋습니다.
  • 24. apply inline fun <T> T.apply(f: T.() -> Unit) : T { f(); return this }
  • 25. apply inline fun <T> T.apply(f: T.() -> Unit) : T { f(); return this } val person = Person().apply { name = "ari" age = 24 }
  • 26. apply inline fun <T> T.apply(f: T.() -> Unit) : T { f(); return this } val person = Person().apply { name = "ari" age = 24 } println(person) //Person(name=ari, age=24)
  • 27. apply inline fun <T> T.apply(f: T.() -> Unit) : T { f(); return this } AlertDialog.Builder(this).apply { setTitle(getString(R.string.title)) setMessage(getString(R.string.message)) setPositiveButton(getString(R.string.ok), { dlg, _ -> dlg.dismiss() }) create() show() }
  • 28. apply inline fun <T> T.apply(f: T.() -> Unit) : T { f(); return this } • type.apply { .. } 을 사용합니다. • type T를 입력받아 { .. } 안을 수행하고 자기 자신을 반환합니다. • 생성과 동시에 추가적인 작업을 해줘야 할 때 유용합니다.
  • 29. run inline fun <R> run(block: () -> R): R = block() inline fun <T, R> T.run(block: T.() -> R) : R = block()
  • 30. run val name = person.run { name } inline fun <R> run(block: () -> R): R = block() inline fun <T, R> T.run(block: T.() -> R) : R = block()
  • 31. run val name = person.run { name } println(name) // myeongin inline fun <R> run(block: () -> R): R = block() inline fun <T, R> T.run(block: T.() -> R) : R = block()
  • 32. run run { sendEmail(name) } inline fun <R> run(block: () -> R): R = block() inline fun <T, R> T.run(block: T.() -> R) : R = block()
  • 33. run • let과 거의 유사합니다. 하지만 let은 T를 인자로 받지만 (T) run은 T.() T의 자신을 블럭 으로 지 정합니다.(this) • 별도로 함수를 만들지 않고 block 을 통해 함수 구문을 만들고 실행 할수 있습니다. • 역시나 마지막줄의 값을 반환합니다. inline fun <R> run(block: () -> R): R = block() inline fun <T, R> T.run(block: T.() -> R) : R = block()
  • 34. also inline fun <T> T.also(block: (T) -> Unit) : T { block(this); return this }
  • 35. also inline fun <T> T.also(block: (T) -> Unit) : T { block(this); return this } person.also { it.name = "ari" } println(person) //Person(name=ari, age=18)
  • 36. also inline fun <T> T.also(block: (T) -> Unit) : T { block(this); return this } • let과 거의 유사합니다. let은 R을 반환 하는 반면 also는 자기자신 T를 반환합니다. • 마지막줄의 값과 상관없이 자기 자신을 반환합니다.
  • 37. let, run, with, also, apply
  • 38. takeIf inline fun <T> T.takeIf(predicate: (T) -> Boolean) : T? = if (predicate(this)) this else null
  • 39. takeIf inline fun <T> T.takeIf(predicate: (T) -> Boolean) : T? = if (predicate(this)) this else null val ari = person.takeIf { it.name == "ari" }
  • 40. takeIf inline fun <T> T.takeIf(predicate: (T) -> Boolean) : T? = if (predicate(this)) this else null val ari = person.takeIf { it.name == "ari" } println(ari) // null
  • 41. takeIf inline fun <T> T.takeIf(predicate: (T) -> Boolean) : T? = if (predicate(this)) this else null val ari = person.takeIf { it.name == "ari" } println(ari) // null val myeongin = person.takeIf { it.name == "myeongin" }
  • 42. takeIf inline fun <T> T.takeIf(predicate: (T) -> Boolean) : T? = if (predicate(this)) this else null val ari = person.takeIf { it.name == "ari" } println(ari) // null val myeongin = person.takeIf { it.name == "myeongin" } println(myeongin) // Person(name=myeongin, age=18)
  • 43. takeIf inline fun <T> T.takeIf(predicate: (T) -> Boolean) : T? = if (predicate(this)) this else null val ari = person.takeIf { it.name == "ari" } println(ari) // null val myeongin = person.takeIf { it.name == "myeongin" } println(myeongin) // Person(name=myeongin, age=18) val default = person.takeIf { it.name == "ari" } ?: Person("ari", 24)
  • 44. takeIf inline fun <T> T.takeIf(predicate: (T) -> Boolean) : T? = if (predicate(this)) this else null val ari = person.takeIf { it.name == "ari" } println(ari) // null val myeongin = person.takeIf { it.name == "myeongin" } println(myeongin) // Person(name=myeongin, age=18) val default = person.takeIf { it.name == "ari" } ?: Person("ari", 24) println(default) // Person(name=ari, age=24)
  • 45. takeUnless inline fun <T> T.takeUnless(predicate: (T) -> Boolean) : T? = if (!predicate(this)) this else null
  • 46. takeUnless inline fun <T> T.takeUnless(predicate: (T) -> Boolean) : T? = if (!predicate(this)) this else null val ari = person.takeUnless { it.name == "ari" }
  • 47. takeUnless inline fun <T> T.takeUnless(predicate: (T) -> Boolean) : T? = if (!predicate(this)) this else null val ari = person.takeUnless { it.name == "ari" } println(ari) // Person(name=myeongin, age=18)
  • 48. takeUnless inline fun <T> T.takeUnless(predicate: (T) -> Boolean) : T? = if (!predicate(this)) this else null val ari = person.takeUnless { it.name == "ari" } println(ari) // Person(name=myeongin, age=18) val myeongin = person.takeUnless { it.name == "myeongin" }
  • 49. takeUnless inline fun <T> T.takeUnless(predicate: (T) -> Boolean) : T? = if (!predicate(this)) this else null val ari = person.takeUnless { it.name == "ari" } println(ari) // Person(name=myeongin, age=18) val myeongin = person.takeUnless { it.name == "myeongin" } println(myeongin) // null
  • 50. takeUnless inline fun <T> T.takeUnless(predicate: (T) -> Boolean) : T? = if (!predicate(this)) this else null val ari = person.takeUnless { it.name == "ari" } println(ari) // Person(name=myeongin, age=18) val myeongin = person.takeUnless { it.name == "myeongin" } println(myeongin) // null val default = person.takeUnless { it.name == "ari" } ?: Person("ari", 24)
  • 51. takeUnless inline fun <T> T.takeUnless(predicate: (T) -> Boolean) : T? = if (!predicate(this)) this else null val ari = person.takeUnless { it.name == "ari" } println(ari) // Person(name=myeongin, age=18) val myeongin = person.takeUnless { it.name == "myeongin" } println(myeongin) // null val default = person.takeUnless { it.name == "ari" } ?: Person("ari", 24) println(default) // Person(name=myeongin, age=18)
  • 52. use // Java 1.6 Properties property = new Properties(); FileInputStream stream = new FileInputStream("config.properties"); try { property.load(steam); } finally { stream.close(); } // Java 1.7 Properties property = new Properties(); try (FileInputStream stream = new FileInputStream("config.properties")) { property.load(stream); } // FileInputStream는 자동으로 close됨
  • 53. use public inline fun <T : Closeable?, R> T.use(block: (T) -> R): R { var closed = false try { return block(this) } catch (e: Exception) { closed = true try { this?.close() } catch (closeException: Exception) { } throw e } finally { if (!closed) { this?.close() } } }
  • 54. use public inline fun <T : Closeable?, R> T.use(block: (T) -> R): R { var closed = false try { return block(this) } catch (e: Exception) { closed = true try { this?.close() } catch (closeException: Exception) { } throw e } finally { if (!closed) { this?.close() } } } val property = Properties() FileInputStream("config.properties").use { property.load(it) } // FileInputStream이 자동으로 close됨.
  • 55. repeat inline fun repeat(times: Int, action: (Int) -> Unit) { for (index in 0..times - 1) { action(index) } }
  • 56. repeat inline fun repeat(times: Int, action: (Int) -> Unit) { for (index in 0..times - 1) { action(index) } } repeat(4, { println("Hello, World") })
  • 57. repeat inline fun repeat(times: Int, action: (Int) -> Unit) { for (index in 0..times - 1) { action(index) } } repeat(4, { println("Hello, World") }) // Hello, World // Hello, World // Hello, World // Hello, World