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

When defining this type of extension function, how can I use arguments( Here, the argument of type String) inside the block?

When defining extension functions at the same time as declaration like this, can only this be used?

ybybyb
  • 1,385
  • 1
  • 12
  • 33

1 Answers1

3

You can access it using it:

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

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

This will output

this = 1
it = a
result = 42

An alternative is to introduce a lambda-parameter:

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

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

This will output

this = 1
s = a
result = 42
enzo
  • 9,861
  • 3
  • 15
  • 38
  • 1
    Thanks for the detailed reply. I thought the argument `s` replaced `this`. I understand well thanks to you. – ybybyb Jun 28 '21 at 18:49