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] 繰り返し関数 Int.times を作成

Last updated at Posted at 2021-12-04

概要

kotlin には既に repeat(n) などの便利な繰り返し関数があるが,個人的に Ruby の n.times が好きなので,拡張関数や高階関数の勉強を兼ねて実装.初心者向け.

実装

結論を先に述べると実装は次のようになる.

Times.kt
fun <T> Int.times(lambda: (Int) -> T) {
  for (i in 0 until this) {
    lambda(i)
  }
}

使い方の例.

Main.kt
fun main() {
  5.times { println(it) }
}
Output
0
1
2
3
4

解説

Kotlin の拡張関数 (extensions) 機能により,既存のクラスに新たな関数を定義できる.例えば,次に示す拡張関数はレシーバとなる Int 型の値と引数 a との積を返す関数である.

fun Int.multi(a: Int): Int = this * a
println(5.multi(4)) // -> 20

そして,Kotlin の高階関数 (High-order function) 機能を併用して,引数に渡されたラムダ式 lambda() をレシーバの値の回数だけ実行する高階関数を定義する.

fun <T> Int.times(lambda: () -> T) {
  for (i in 0 until this) {
    lambda()
  }
}

パラメーターのラムダ式 lambda() に,何回目の処理であるかを示すパラメーター it: Int を定義することで,times 関数を呼び出すときにラムダ式の中で利用できる.この場合,ラムダ式のパラメーターが 1 つなので宣言を省略して it として使用できる

fun <T> Int.times(lambda: (Int) -> T) {
  for (i in 0 until this) {
    lambda(i)
  }
}

fun main() {
  5.times { println(it) }
}

定義に従うと次のような呼び出し方ができるが,

5.times( { println(it) } )

According to Kotlin convention, if the last parameter of a function is a function, then a lambda expression passed as the corresponding argument can be placed outside the parentheses

とのことなので,次のように変形できる.

5.times{ println(it) }
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?