SAM is the abbreviation for single abstract method, which is that some interfaces have only one abstract approach
Let's say we need to make a button that records the number of clicks in the background whenever the button is pressed. In Java, the code is implemented in the following way:
Package com.dt.scala.funcimport javax.swing.jbuttonimport java.awt.event.actionlistenerimport java.awt.event.actioneventimport javax.swing.jframeobject sam { def main ( Args: array[string]): unit = { var data = 0 val frame = new jframe ("sam testing"); val jButton = new jbutton ("Counter") jbutton.addactionlistener (new actionlistener { override def actionperformed (event: actionevent) {     DATA += 1      PRINTLN (data) } }) frame.setcontentpane (JButton); frame.pack (); frame.setvisible (True); }}
Jbuttton.addactionlistener in the code, we only care about
Data + = 1PRINTLN (data)
The other is the boilerplate code, each time to repeat the write. In Scala, we can use implicit conversions to simplify the notation. As follows
Package com.dt.scala.funcimport javax.swing.jbuttonimport java.awt.event.actionlistenerimport java.awt.event.actioneventimport javax.swing.jframeobject sam { def main ( Args: array[string]): unit = { var data = 0 val frame = new jframe ("sam testing"); val jbutton = new jbutton ("Counter") implicit def Convertedaction (action: (actionevent) => unit) = new actionlistener { override def actionperformed (event: ActionEvent) { action (event) } } jbutton.addactionlistener (event: actionevent) => {data += 1; println (data)}) fraMe.setcontentpane (JButton); frame.pack (); frame.setvisible (true); }}
Our functional code is simplified to
Jbutton.addactionlistener ((event:actionevent) = {data + = 1; println (data)})
This feature is called Sam conversion.
This article is from the "Ding Dong" blog, please be sure to keep this source http://lqding.blog.51cto.com/9123978/1741886
24th: A walkthrough of Sam conversion in Scala