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

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.

主站蜘蛛池模板: 宜章县| 安图县| 绍兴市| 蓝田县| 峨山| 汉沽区| 南宁市| 安西县| 山西省| 曲松县| 七台河市| 平凉市| 五河县| 商河县| 莱西市| 台北县| 松滋市| 德兴市| 得荣县| 临沧市| 玛沁县| 三河市| 上林县| 临高县| 甘肃省| 乌鲁木齐市| 油尖旺区| 旌德县| 马公市| 乌兰县| 岐山县| 九龙城区| 镇江市| 泸定县| 惠水县| 无为县| 彰武县| 鹤岗市| 西峡县| 璧山县| 九龙县|