Kotlin Expression, Scope and Visibility modifiers tutorial

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.


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 in Lesson 5 ( Higher Order Functions and Functional Programming ).

class Building(val address: String) {
      inner class Reception(telephone: String) {
        fun printAddress() = println(this@Building.address)

Note the print function needed to qualify access to the Building outer instance. This is because this inside the
printAddress() function would have referred to the closest containing class, which in this case is Reception. Do not worry about the inner keyword that will be covered in Lesson 3 ( Object Oriented Programming in Kotlin ).

Visibility modifiers

Usually not all functions or classes are designed to be part of your public API. Therefore, it is desirable to mark some parts of your code as internal and not accessible outside of the class or package. The keywords that are used to specify this are called visibility modifiers.
There are four visibility modifiers: Public, internal, protected, and private. If no modifier is given, then the default is used, which is public. This means they are fully visible to any code that wishes to use them.
Java developers will know that this contrasts to the Java default, which has package-level visibility.

It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn