Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It is not possible in scala to require an implicit conversion to exist for a type parameter of a trait. There is a good reason for this. Suppose we defined a trait like:</p> <pre><code>trait ATrait[T &lt;% Int] { def method(v: T) { println(v: Int) } } </code></pre> <p>And then made instances of it in two places:</p> <pre><code>package place1 { implicit def strToInt(s: String) = 5 val inst = new ATrait[String] } package place2 { implicit def strToInt(s: String) = 6 val inst = new ATrait[String] } </code></pre> <p>And then used these instances like:</p> <pre><code>val a = if (someTest) place1 else place2 a.method("Hello") </code></pre> <p>Should this print <code>5</code> or <code>6</code>? That is, which implicit conversion should it use? Implicits have to be found at compile time, but you don't know which implicit conversion was present for the creation of the object.</p> <p>In other words, implicits are provided by the scope in which they are used, not by the objects they are used on; the latter would be impossible.</p> <p>So, about your problem. Instead of using an implicit, you could use an ordinary member:</p> <pre><code>trait Summable[T] { def -= (v: T): Unit def -= (v: Int) { this -= (encode(v)) } def encode(i: Int): T } class Int4 (var x: Int, var y: Int, var z: Int, var w: Int) extends Summable[Int4] { def -= (v : Int4) : Unit = { x -= v.x; y -= v.y; z -= v.z; w -= v.w } def encode(i: Int) = Int4.int2Int4(i) } </code></pre> <p>Now the <code>decrement</code> method compiles correctly.</p> <p>Another way of saying this is, don't think of implicits as properties belonging to a type (ie, "can be implicitly converted from an Int" isn't a property of Int4). They are values, which can be identified using types.</p> <p>Hope this helps.</p>
    singulars
    1. This table or related slice is empty.
    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