Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The problem results of a combination of Scalas type inference algorithm and the way how <code>Option.fold</code> is defined.</p> <p>Scalas type inference works from left to right, this means that it starts with the leftmost symbol to search for a possible type for an expression. Further, for method parameter lists this means, that a generic type is bound to the type filled in by the leftmost parameter list:</p> <pre><code>scala&gt; def meth[A](a1: A, a2: A) = (a1, a2) meth: [A](a1: A, a2: A)(A, A) scala&gt; meth(1, "") res7: (Any, Any) = (1,"") scala&gt; def meth[A](a1: A)(a2: A) = (a1, a2) meth: [A](a1: A)(a2: A)(A, A) scala&gt; meth(1)("") &lt;console&gt;:10: error: type mismatch; found : String("") required: Int meth(1)("") ^ </code></pre> <p>As one can see, in the first case <code>Any</code> is inferred, whereas in the second case a compiler error is thrown because the type of <code>A</code> is bound by the first parameter list and the second one can't change it any more.</p> <p>But in order to get he method call in the question to work, the type of the resulting <code>Option</code> may not defined until the second parameter list is reached. Because this requires a right to left type inference hence the error. This is somewhat identical to <code>List.fold</code>:</p> <pre><code>scala&gt; List(1).foldLeft(Nil)((xs,x) =&gt; x::xs) &lt;console&gt;:8: error: type mismatch; found : List[Int] required: scala.collection.immutable.Nil.type List(1).foldLeft(Nil)((xs,x) =&gt; x::xs) ^ </code></pre> <p>To get the code to work one has to explicitly specify the type of the resulting collection, see <a href="https://stackoverflow.com/a/12321634/465304">@rks answer</a> for an example.</p> <p>See the discussion <a href="https://groups.google.com/forum/#!topic/scala-language/35EcioxSQ50" rel="nofollow noreferrer">here</a> for the full explanation why it is defined as it is defined. In short: <code>Option</code> follows the design of collections in a lot of respects - thus it is more clear when it behaves the same way as collections do.</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