Frage

I've been reading this chapter from a Scala book and it says that:

pressing a button will create an event which is an instance of the following case class:
case class ButtonClicked(source: Button)

The parameter of the case class refers to the button that was clicked. As with all other Scala Swing events, this event class is contained in a package named scala.swing.event.

and then this code, where b is the actual button that was pressed:

case ButtonClicked(b) => //code

I looked at the API and sure enough, there was a constructor for ButtonPressed:

new ButtonClicked(source: AbstractButton) 

So what happens to a mouse event, for example mousePressed? You usually do this in the code:

1) case e: MousePressed => // code//

Does that mean the below can also be done? Are they the same?

2) case MousePressed(e: java.awt.event.MouseEvent)

What's the difference between 1 and 2?

EDIT:

Is 1) also a case class? You don't have to pass a parameter into it?

War es hilfreich?

Lösung

Being a case class is just that - it's an inherent quality of the class, not dependent on how you use it. As you can see, MousePressed is defined as a case class (and it's not a subclass of Java's MouseEvent BTW, in case that causes confusion), so it's always a case class.

1 and 2 are simply different pattern matching expressions. The difference is that:

  • you can use 1 for any type, since you're basically saying "match anything that is an instance of the type MousePressed",
  • for 2 you need something called an extractor - it tells Scala how to decompose the pattern you've provided. Case classes have constructor-derived extractors defined "for free", and that's why you're able to use 2 on MousePressed.

In summary - read up the previous chapter on case classes and pattern matching - everything will become clearer.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top