Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I think the reason Scala requires the type annotation on the parameters of a newly defined function comes from the fact that Scala uses a more local type inference analysis than that used in Haskell.</p> <p>If all your classes mixed in a trait, say <code>Addable[T]</code>, that declared the <code>+</code> operator, you could write your generic add function as:</p> <pre><code>def add[T &lt;: Addable[T]](x : T, y : T) = x + y </code></pre> <p>This restricts the add function to types T that implement the Addable trait.</p> <p>Unfortunately, there is not such trait in the current Scala libraries. But you can see how it would be done by looking at a similar case, the <code>Ordered[T]</code> trait. This trait declares comparison operators and is mixed in by the <code>RichInt</code>, <code>RichFloat</code>, etc. classes. Then you can write a sort function that can take, for example, a <code>List[T]</code> where <code>[T &lt;: Ordered[T]]</code> to sort a list of elements that mix in the ordered trait. Because of implicit type conversions like <code>Float</code> to <code>RichFloat</code>, you can even use your sort function on lists of <code>Int</code>, or <code>Float</code> or <code>Double</code>.</p> <p>As I said, unfortunately, there is no corresponding trait for the <code>+</code> operator. So, you would have to write out everything yourself. You would do the Addable[T] trait, create <code>AddableInt</code>, <code>AddableFloat</code>, etc., classes that extend Int, Float, etc. and mix in the Addable trait, and finally add implicit conversion functions to turn, for example, and Int into an <code>AddableInt</code>, so that the compiler can instantiate and use your add function with it.</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.
 

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