reset password
Author Message
rabbott
Posts: 1649
Posted 16:33 Nov 15, 2013 |

You have probably noticed that in the videos many methods are called without dots. That's another of Scala's ways to make code look more natural.  Suppose you wanted to find the smaller of corresponding elements in two lists.

  val ns = (1 to 5).toList          //> ns  : List[Int] = List(1, 2, 3, 4, 5)
  val reverseNs = ns.reverse        //> reverseNs  : List[Int] = List(5, 4, 3, 2, 1)
  ns.zip(reverseNs).map( { case (x, y) => x.min(y) } )
                                    //> res14: List[Int] = List(1, 2, 3, 2, 1)

The final line could also be written like this.

  (ns zip reverseNs) map ( { case (x, y) => x min y } )
                                    //> res15: List[Int] = List(1, 2, 3, 2, 1)

The intent is to make zip and min look like binary operators (like + and *) rather than like methods. 

Note also the convenience of using a case construct in the anonymous function. Without it you would have to write either

(ns zip reverseNs) map (xy => xy match case (x, y) => x min y } )

or

(ns zip reverseNs) map (xy => xy._1 min xy._2 })

Note that to use a case construct in this way requires that you surround it with braces. It's really a shortened for the full match version.

 

Last edited by rabbott at 16:39 Nov 15, 2013.