Kotlin: 関数を別の関数にパラメータとして渡すにはどうすればいいですか? 質問する

Kotlin: 関数を別の関数にパラメータとして渡すにはどうすればいいですか? 質問する

与えられた関数 foo:

fun foo(m: String, bar: (m: String) -> Unit) {
    bar(m)
}

我々はできる:

foo("a message", { println("this is a message: $it") } )
//or 
foo("a message")  { println("this is a message: $it") }

ここで、次の関数があるとします。

fun buz(m: String) {
   println("another message: $m")
}

「buz」を「foo」のパラメータとして渡す方法はありますか? 次のような感じです:

foo("a message", buz)

ベストアンサー1

::関数参照を示すために使用し、次の操作を実行します。

fun foo(msg: String, bar: (input: String) -> Unit) {
    bar(msg)
}

// my function to pass into the other
fun buz(input: String) {
    println("another message: $input")
}

// someone passing buz into foo
fun something() {
    foo("hi", ::buz)
}

Kotlin 1.1以降関数参照演算子の前にインスタンスを付けることで、クラス メンバーである関数 (「バインドされた呼び出し可能参照」) を使用できるようになりました。

foo("hi", OtherClass()::buz)

foo("hi", thatOtherThing::buz)

foo("hi", this::buz)

おすすめ記事