Description
Objects with
invoke()method can be invoked as a function.You can add
invokeextension for any class, but it's better not to overuse it:
invoke()メソッドを持つオブジェクトは、関数として呼び出すことができます。どのクラスにも
invoke拡張は追加することができますが、あまり使いすぎないことをおすすめします。
fun Int.invoke() { println(this) }
1() //huh?..
Implement the function
Invokable.invoke()so it would count a number of invocations.
関数
Invokable.invoke()を実装し、関数の呼び出し回数をカウントするようにしてください。
Code
class Invokable {
var numberOfInvocations: Int = 0
private set
operator fun invoke(): Invokable {
numberOfInvocations++
return this
}
}
fun invokeTwice(invokable: Invokable) = invokable()()
Memo
invoke()でinvoke()メソッドを呼び出すinvoke(x: Int)のように引数をとり、invokable(1)(2)とすることもできる
invokable()()
// invokeは省略できる。省略しない場合
invokable.invoke().invoke()