0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

kotlinラムダ式

Last updated at Posted at 2020-11-12
  1. ラムダ式、つまり関数型リテラルの完全な構文形式
val sum = { x: Int, y: Int -> x + y }
  1. 発展
val sum: (Int, Int) -> Int = { x, y -> x + y }
  1. 高階関数

Kotlinでは、関数の最後のパラメータが関数である場合、そのパラメータは括弧の外に指定することができるという慣習があります

//定義
fun <T, R> List<T>.map(transform: (T) -> R): List<R> {
  val result = arrayListOf<R>()
  for (item in this)
    result.add(transform(item))
  return result
}

//呼び出し
val doubled = ints.map { it -> it * 2 }

関数内のラムダ式で return すると通常は関数から戻りますが、@ でラベル指定することで、ラムダ式を return することが可能。returnするときに返り値が必要な関数もある。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?