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

问题描述

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...