- Learn Kotlin Programming(Second Edition)
- Stephen Samuel Stefan Bocutiu
- 136字
- 2021-06-24 14:13:28
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 as discussed in Chapter 5, Higher-Order Functions and Functional Programming.
Consider the following code:
class Building(val address: String) { inner class Reception(telephone: String) { fun printAddress() = println(this@Building.address) } }
Note that 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 Chapter 3, Object-oriented Programming in Kotlin.
推薦閱讀
- Web全棧工程師的自我修養
- 深度學習:算法入門與Keras編程實踐
- Unity 5.x By Example
- 程序員修煉之道:通向務實的最高境界(第2版)
- Visual Studio Code 權威指南
- Clean Code in C#
- GitHub入門與實踐
- IoT Projects with Bluetooth Low Energy
- Python Projects for Kids
- Python數據科學實踐指南
- MongoDB Cookbook
- 零基礎學Java(第5版)
- Game Development Patterns and Best Practices
- Getting Started with SQL Server 2014 Administration
- Python3從入門到實戰