应用程序没有 `apply` 方法?
Application without the `apply` method?
我在 org.scalacheck.Properties
文件中注意到以下代码:
/** 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") = ...
时发生了什么。 classPropertySpecifier
中没有apply
方法。那么,这里叫什么?
您可能会注意到,该用法不仅显示应用程序,还显示其他内容,即 =
符号。通过让 class 实现 update
方法,您可以让编译器如何更新此 class 的 state 并允许 property("myProp") =
语法。
您可以在 Array
上找到相同的行为,其中 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
我在 org.scalacheck.Properties
文件中注意到以下代码:
/** 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") = ...
时发生了什么。 classPropertySpecifier
中没有apply
方法。那么,这里叫什么?
您可能会注意到,该用法不仅显示应用程序,还显示其他内容,即 =
符号。通过让 class 实现 update
方法,您可以让编译器如何更新此 class 的 state 并允许 property("myProp") =
语法。
您可以在 Array
上找到相同的行为,其中 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