定义扩展函数时如何在块内使用参数?

问题描述

val test: Int.(String) -> Int = {
  plus((this))
}
        

定义这种类型的extension function时,如何在块内使用arguments( Here,the argument of type String)

像这样在声明的同时定义extension functions时,只能使用this吗?

解决方法

您可以使用 it 访问它:

val test: Int.(String) -> Int = {
  println("this = $this")
  println("it = $it")
  42
}

fun main() {
    println("result = " + 1.test("a"))
}

这将输出

this = 1
it = a
result = 42

另一种方法是引入一个 lambda 参数:

val test: Int.(String) -> Int = { s ->
  println("this = $this")
  println("s = $s")
  42
}

fun main() {
    println("result = " + 1.test("a"))
}

这将输出

this = 1
s = a
result = 42