- Functional Kotlin
- Mario Arias Rivu Chakraborty
- 219字
- 2021-06-24 19:15:22
Objects
We already covered object expressions, but there is more on objects. Objects are natural singletons (by natural, I mean to come as language features and not as behavior pattern implementations, as in other languages). A singleton is a type that has just one and only one instance and every object in Kotlin is a singleton. That opens a lot of interesting patterns (and also some bad practices). Objects as singletons are useful for coordinating actions across the system, but can also be dangerous if they are used to keep global state.
Object expressions don't need to extend any type:
fun main(args: Array<String>) {
val expression = object {
val property = ""
fun method(): Int {
println("from an object expressions")
return 42
}
}
val i = "${expression.method()} ${expression.property}"
println(i)
}
In this case, the expression value is an object that doesn't have any specific type. We can access its properties and functions.
There is one restriction—object expressions without type can be used only locally, inside a method, or privately, inside a class:
class Outer {
val internal = object {
val property = ""
}
}
fun main(args: Array<String>) {
val outer = Outer()
println(outer.internal.property) // Compilation error: Unresolved reference: property
}
In this case, the property value can't be accessed.
- Raspberry Pi for Python Programmers Cookbook(Second Edition)
- Learning Real-time Processing with Spark Streaming
- 測試驅動開發:入門、實戰與進階
- Power Up Your PowToon Studio Project
- PaaS程序設計
- 云原生Spring實戰
- Django Design Patterns and Best Practices
- 零基礎學MQL:基于EA的自動化交易編程
- Easy Web Development with WaveMaker
- JS全書:JavaScript Web前端開發指南
- Visual Basic程序設計實驗指導(第4版)
- 精通Python自動化編程
- 零基礎學C語言第2版
- Python語言科研繪圖與學術圖表繪制從入門到精通
- Flask Web開發:基于Python的Web應用開發實戰(第2版)