Search code examples
scalascala-swing

Why scala-swing Button can be assigned to MainFrame's contents?


In scala-swing, I can write this simple code:

import scala.swing._

object HelloWorld2 extends SimpleSwingApplication {
  val top = new MainFrame()
  top.title = "Hello, World!"
  top.contents = new Button("a")
}

it works fine but according to doc the type of contents in MainFrame is Seq[Component] whilst the type of Button is Button. So why can I write

top.contents = new Button("a")

without error?


Solution

  • Note the following two method signatures as per API docs

    def contents: Seq[Component]
    def contents_=(c: Component): Unit
    

    The assignment syntax

    top.contents = new Button("a")
    

    actually makes use of mutator _= method

    def contents_=(c: Component): Unit
    

    as explained by Accessors/Mutators

    For mutators, the name of the method should be the name of the property with “_=” appended. As long as a corresponding accessor with that particular property name is defined on the enclosing type, this convention will enable a call-site mutation syntax which mirrors assignment.