2017-12-25 10 views
1

Kotlin Koan 질문 ( https://github.com/Kotlin/kotlin-koans/blob/master/src/ii_collections/n16FlatMap.kt)에서이 Koan 코드가 있습니다. 어떻게 읽습니까? val 인 변수처럼 보이지만, (){} 인 함수입니다.val ... get() {...} in Kotlin

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

은 암시 적 게터처럼 보입니다. – njzk2

+1

https://kotlinlang.org/docs/reference/properties.html에 문서화되어 있습니다. –

답변

3

이것은 읽기 전용 계산 된 확장 속성입니다. get 메서드는 값을 계산하기 위해 호출되는 메서드입니다.

따라서 그것은 사용할 수 있습니다

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

속성으로 구성원을 처리 할 수있는 기회를 허용하는 것 같다. 이 예제에서는 Customer.orderedProducts 속성에서 문자열을 가져올 수 있습니다.

data class Customer(val name: String, val orders: List<String>) 

val Customer.orderedProducts: String get() { 
    return this.orders.joinToString() 
} 

fun main(args: Array<String>) { 
    val c = Customer("hello", arrayListOf("A", "B")) 
    println(c.orderedProducts) 
    println(c.orders) 
} 

출력 값입니다.