Last active
December 2, 2016 15:35
-
-
Save omochi/f00ec35d294e03a93494464968bc1d54 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// こんなふうにメソッドをいろいろ呼び出して設定するようなやつがいるときに | |
class HogeBuilder { | |
fun configureAaa() { println("a") } | |
fun configureBbb() { println("b") } | |
fun configureCcc() { println("c") } | |
} | |
// こういう、「Tを引数にとる関数」があると | |
fun <T> myLet(x: T, f: (T)->Unit) { | |
f(x) | |
} | |
// こんなふうに | |
fun example1( ) { | |
// 長い変数名をつけてても | |
val hogeBuilder = HogeBuilder() | |
// itに束縛して短くかけて嬉しい | |
// スコープも切れるので途中計算用のローカル変数とかも | |
// example1のスコープを汚さずに作れて便利 | |
myLet(hogeBuilder) { | |
it.configureAaa() | |
it.configureBbb() | |
it.configureCcc() | |
} | |
} | |
// ここでさっきのmyLetのfの型を「Tのメソッドの型の関数」にしてやると | |
fun <T> myWith(x: T, f: T.()->Unit) { | |
x.f() | |
} | |
// こんなふうに | |
fun example2( ) { | |
// 長い変数名があっても | |
val hogeBuilder = HogeBuilder() | |
// itすらいらなくなる! | |
// クロージャが「メソッドの型」なので、 | |
// thisが省略されている | |
myWith(hogeBuilder) { | |
configureAaa() | |
configureBbb() | |
configureCcc() | |
} | |
} | |
// この機能を使って下記のように型安全なDSL、みたいなこともできる | |
// http://kotlinlang.org/docs/reference/type-safe-builders.html | |
fun main(args: Array<String>) { | |
example1() | |
example2() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment