Book Image

Programming Kotlin

Book Image

Programming Kotlin

Overview of this book

Quickly learn the fundamentals of the Kotlin language and see it in action on the web. Easy to follow and covering the full set of programming features, this book will get you fluent in Kotlin for Android.
Table of Contents (20 chapters)
Programming Kotlin
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Customer Feedback
Preface

This expression


When inside a class or function, we often want to refer to the enclosing instance. For example, an instance may want to invoke a method passing itself as an argument. To do this, we use the keyword this:

    class Person(name: String) {
      fun printMe() = println(this) 
    } 

In Kotlin terminology, the reference referred to by the this keyword is called the current receiver. This is because it was the instance that received the invocation of the function. For example, if we have a string and invoke length, the string instance is the receiver.

In members of a class, this refers to the class instance. In extension functions, this refers to the instance that the extension function was applied to.

Scope

In nested scopes, we may wish to refer to an outer instance. To do that, we must qualify the usage of this, and we do that using labels. The label we use is typically the name of the outer class, but there are more complicated rules for functions and closures discussed...