val ... get() {...} in Kotlin


#1

From the Kotlin Koan question(
https://github.com/Kotlin/kotlin-koans/blob/master/src/ii_collections/n16FlatMap.kt), I have this Koan code. How do I read this? It looks like a variable with val, but it is a function with a () and {}.

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

#2

It’s a read-only extension property of the Customer type called orderedProducts.

It returns a Set<Product> and has an explicit getter i.e. a function with signature get() to obtain the value of the property.

It’s sometimes easier to read these if the getter - suitably indented - is placed on the next line.

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