2017-07-04 67 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 
相关问题