2017-07-04 69 views
1

我注意到下面的代碼在org.scalacheck.Properties文件:沒有`apply`方法的應用程序?

/** Used for specifying properties. Usage: 
    * {{{ 
    * property("myProp") = ... 
    * }}} 
    */ 
    class PropertySpecifier() { 
    def update(propName: String, p: Prop) = props += ((name+"."+propName, p)) 
    } 

    lazy val property = new PropertySpecifier() 

我不知道什麼時候被調用property("myProp") = ...發生了什麼。 PropertySpecifier中沒有apply方法。那麼,這裏叫什麼?

回答

1

您可能會注意到,該用法不僅顯示應用程序,而且顯示其他內容,=符號。通過讓您的課程實現update方法,您可以讓編譯器如何更新此類的狀態並允許使用property("myProp") =語法。

您可以在Array s上找到相同的行爲,其中apply執行讀訪問和update寫訪問。

這裏是一個小例子,你可以用它來明白這一點:

final class Box[A](private[this] var item: A) { 

    def apply(): A = 
    item 

    def update(newItem: A): Unit = 
    item = newItem 

} 

val box = new Box(42) 
println(box()) // prints 42 
box() = 47 // updates box contents 
println(box()) // prints 47 
相關問題