title: What is happening under the covers in this scala code?
body: <p>I have the following scala code (from the FP In Scala book):</p>
  
  <pre><code>import scala.{Option =&gt; _, Either =&gt; _, Left =&gt; _, Right =&gt; _, _} // hide std library `Option` and `Either`, since we are writing our own in this chapter
  
  case class Left[+E](get: E) extends Either[E,Nothing]
  case class Right[+A](get: A) extends Either[Nothing,A]
  
  sealed trait Either[+E,+A] {
   def map[B](f: A =&gt; B): Either[E, B] = this match {
     case Right(r) =&gt; Right(f(r))
     case Left(e) =&gt; Left(e)
   }
  
   def flatMap[EE &gt;: E, B](f: A =&gt; Either[EE, B]): Either[EE, B] = this match {
     case Right(r) =&gt; f(r)
     case Left(e) =&gt; Left(e)
   }
  
   def map2[EE &gt;: E, B, C](b: Either[EE, B])(f: (A, B) =&gt; C): Either[EE, C] = {
      this flatMap(aa =&gt; b map (bb =&gt; f(aa, bb)))
   }
  
  }
  </code></pre>
  
  <p>I would like to know what is going on when I call map2 like this:</p>
  
  <pre><code>val b = fpinscala.errorhandling.Right(2)
  val a = fpinscala.errorhandling.Right("right")
  val f = (a: String, b:Int) =&gt; a + b
  a.map2(b)(f)
  </code></pre>
  
  <p>How does scala know to use substitute <code>this</code> (i.e. <code>a</code>) into the <code>aa</code> in this line of code: <code>this flatMap(aa =&gt; b map (bb =&gt; f(aa, bb)))</code> in the <code>map2</code> function? </p>