val … get(){…}在Kotlin

从Kotlin Koan问题( https://github.com/Kotlin/kotlin-koans/blob/master/src/ii_collections/n16FlatMap.kt ),我有这个Koan代码。 我如何阅读这个? 它看起来像一个val的variables,但是它是一个带有(){}的函数。

 val Customer.orderedProducts: Set get() { // Return all products this customer has ordered todoCollectionTask() } 

它是一个只读的计算扩展属性。 get方法就是所谓的计算值。

它可以这样使用:

 yourCustomer.orderedProducts.first() // ^ You're implicitly calling the get() method. 

似乎允许有机会将会员作为财产处理。 在这个例子中,我可以从Customer.orderedProducts属性中获取字符串。

 data class Customer(val name: String, val orders: List) val Customer.orderedProducts: String get() { return this.orders.joinToString() } fun main(args: Array) { val c = Customer("hello", arrayListOf("A", "B")) println(c.orderedProducts) println(c.orders) } 

这些是输出值。

 A, B [A, B]