this
As with Java, Kotlin uses this
as a pseudo-property to refer to the instance of the object in whose function you happen to be running.
You can use that as a prefix for property references or function calls, such as this.count
:
class Foo {
var count = 0
fun something() {
this.count += 1
println("something() was called $count times")
}
}
fun main() {
val foo = Foo()
foo.something()
foo.something()
foo.something()
println("the final count was ${foo.count}")
}
Or you could use it on its own to refer to the current instance, such as for supplying that object as a parameter to a function:
class Foo {
fun printMe() {
println(this)
}
}
fun main() {
val foo = Foo()
foo.printMe()
}
Occasionally, you will see odd variants of this
, such as this@Foo
. We will see what that syntax means later in the book.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.