Search code examples
scalascalacheck

Application without the `apply` method?


I noticed the following code in org.scalacheck.Properties file:

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

  lazy val property = new PropertySpecifier()

I'm not sure what is happening when property("myProp") = ... is invoked. There is no apply method in the class PropertySpecifier. So, what is being called here?


Solution

  • You may notice that the usage does not only show application but rather something else, the = sign. By having your class implement an update method you can let the compiler how the state of this class can be updated and allowing the property("myProp") = syntax.

    You can find the same behavior on Arrays, where apply performs read access and update write access.

    Here is a small example you can use to understand this:

    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