- 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.
- JavaScript 網頁編程從入門到精通 (清華社"視頻大講堂"大系·網絡開發視頻大講堂)
- Cassandra Design Patterns(Second Edition)
- SSM輕量級框架應用實戰
- Python:Master the Art of Design Patterns
- concrete5 Cookbook
- Python全棧數據工程師養成攻略(視頻講解版)
- 實戰Java高并發程序設計(第2版)
- 青少年學Python(第2冊)
- 數據結構:Python語言描述
- Android應用開發攻略
- Learning ROS for Robotics Programming
- 基于Docker的Redis入門與實戰
- Mastering Responsive Web Design
- R語言編程基礎
- 亮劍C#項目開發案例導航