https://kotlinlang.org logo
#getting-started
Title
# getting-started
v

Vitali Plagov

12/21/2021, 1:13 PM
I want to create an extension function that is using the
apply{}
function inside. Like:
Copy code
fun Foo.myFun() {
  bar.apply {
    this.doA()
    this.doB()
    this.doC()
  }
}
this
here refers to the type of
bar
, not to the type of
Foo
How can I use the instance of
Foo
inside the
bar.apply{}
?
j

Joffrey

12/21/2021, 1:17 PM
You can use the labeled syntax
this@myFun
to refer to the receiver of the function. But this is only necessary if there is an ambiguity. You can also not use
this
at all and simply call the methods/properties of
Foo
directly
v

Vitali Plagov

12/21/2021, 1:40 PM
Thanks! Didn’t that I can call functions of
Foo
w/o specifying
this
explicitly
j

Joffrey

12/21/2021, 1:43 PM
Yep, in Kotlin in general (like in Java) using
this
is optional, unlike in JS. It's only necessary when there is ambiguity
2 Views