Skip to content

Instantly share code, notes, and snippets.

@k4zy
Created May 22, 2017 09:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save k4zy/96a250e3fd2c0738f6706c654f2673b7 to your computer and use it in GitHub Desktop.
Save k4zy/96a250e3fd2c0738f6706c654f2673b7 to your computer and use it in GitHub Desktop.

スコープ関数とデリゲーションについて

拡張関数について

kotlinは任意のクラスに後からメソッドを追加できます。これを拡張関数と呼びます。

fun String.print() {
  System.out.println(this)
}

val text = "Hello"
text.print()
// > Hello

スコープ関数とは

Kotlinの標準ライブラリには「スコープ関数」と呼ばれる4つの拡張関数があります。 スコープ関数は特定の型ではなく、ジェネリクスで定義されているため全てのクラスで利用可能です。 (withもありますがほとんど使わないので省略します)

  • apply
  • let
  • run
  • also

with

定義

public inline fun <T, R> with(receiver: T, f: T.() -> R): R = receiver.f()
val s = with("hoge") { toUpperCase() }

apply

定義

fun <T> T.apply(block: T.() -> Unit): T
val arguments = Bundle().apply { putString(ARGS_NAME, name) }

let

定義

fun <T, R> T.let(block: (T) -> R): R
adapter.clickSubject
        .subscribe({ SampleDialogFragment.show(it, this) })
        .let { compositeDisposable.add(it) }

run

定義

fun <T, R> T.run(block: T.() -> R): R
val intent
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment