Nabegh Nabegh - 10 months ago 58
Scala Question

Scala map method syntax

The code below from to do matrix dot product.

I can't understand the syntax between the curly brackets.

  • Why are the curly brackets used, not the regular method parentheses?

  • Is t an anonymous method?

  • What is ._1 and ._2?


type Row = List[Double]
type Matrix = List[Row]

def dotProd(v1:Row, v2:Row) ={ t:(Double, Double) => t._1 * t._2 }.reduceLeft(_ + _)

Answer Source
  • Why are the curly brackets used, not the regular method parentheses?

Some people prefer to use curly braces when the parameter is an anonymous function. For one thing, curly braces enable pattern matching anonymous functions, whereas parenthesis do not. In this particular example, there's no need for curly braces.

Here's an example where curly braces are required (because of the case pattern matching):

def dotProd(v1:Row, v2:Row) ={ case (a, b) => a * b }.reduceLeft(_ + _)

Note that the above function accomplishes the same thing as the one in the question, in a slightly different way.

  • Is t an anonymous method?

No, it is a parameter. Just like v1 and v2 are parameters for dotProd, t is a parameter for the anonymous function being passed to map.

  • What is ._1 and ._2?

Methods on t. The parameter t was defined as being a tuple (specifically, Tuple2[Double, Double], which can be written as (Double, Double)), and tuples let you extract each member of the tuple with methods like that: _1, _2, _3, etc.

A Tuple2 only has _1 and _2, of course. Note that the first parameter is _1, not _0, because of influence from other functional languages.

Anyway, the zip method will convert Row (List[Double]) into a List[(Double, Double)]. The method map takes a function that converts the elements of the list (which are (Double, Double) tuples) into something else.