官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 黄骅市| 新干县| 榆社县| 平山县| 青岛市| 根河市| 松桃| 临高县| 准格尔旗| 汉阴县| 武义县| 垫江县| 崇文区| 东乌珠穆沁旗| 霸州市| 枞阳县| 曲靖市| 峨山| 海阳市| 天台县| 榆树市| 佳木斯市| 新宁县| 渭源县| 翼城县| 营口市| 宜春市| 台安县| 福清市| 年辖:市辖区| 珲春市| 固阳县| 宣武区| 德格县| 馆陶县| 车险| 永善县| 垦利县| 巩留县| 商水县| 土默特右旗|