Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>To complete 0_'s answer, <code>fibonacci</code> is being instanciated through the apply method of <code>Memo</code>'s companion object, generated automatically by the compiler since <code>Memo</code> is a case class.</p> <p>This means that the following code is generated for you:</p> <pre><code>object Memo { def apply[A, B](f: A =&gt; B): Memo[A, B] = new Memo(f) } </code></pre> <p>Scala has special handling for the <code>apply</code> method: its name needs not be typed when calling it. The two following calls are strictly equivalent:</p> <pre><code>Memo((a: Int) =&gt; a * 2) Memo.apply((a: Int) =&gt; a * 2) </code></pre> <p>The <code>case</code> block is known as pattern matching. Under the hood, it generates a partial function - that is, a function that is defined for some of its input parameters, but not necessarily all of them. I'll not go in the details of partial functions as it's beside the point (<a href="http://nrinaudo.github.io/blog/2013/08/03/partial-functions/" rel="nofollow">this</a> is a memo I wrote to myself on that topic, if you're keen), but what it essentially means here is that the <code>case</code> block is in fact an instance of <a href="http://www.scala-lang.org/api/current/index.html#scala.PartialFunction" rel="nofollow">PartialFunction</a>.</p> <p>If you follow that link, you'll see that <code>PartialFunction</code> extends <a href="http://www.scala-lang.org/api/current/index.html#scala.Function1" rel="nofollow">Function1</a> - which is the expected argument of <code>Memo.apply</code>.</p> <p>So what that bit of code actually means, once desugared (if that's a word), is:</p> <pre><code>lazy val fibonacci: Memo[Int, BigInt] = Memo.apply(new PartialFunction[Int, BigInt] { override def apply(v: Int): Int = if(v == 0) 0 else if(v == 1) 1 else fibonacci(v - 1) + fibonacci(v - 2) override isDefinedAt(v: Int) = true }) </code></pre> <p>Note that I've vastly simplified the way the pattern matching is handled, but I thought that starting a discussion about <code>unapply</code> and <code>unapplySeq</code> would be off topic and confusing.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload