Uploaded image for project: 'Scala Programming Language'
  1. Scala Programming Language
  2. SI-2509

Contravariance mucks with implicit resolution

    Details

    • Type: Bug
    • Status: Open
    • Priority: Major
    • Resolution: Unresolved
    • Affects Version/s: None
    • Fix Version/s: Backlog
    • Component/s: Compiler (Misc)
    • Labels:
      None
    • Environment:

      implicits variance

      Description

      A condition under which the most-specific implicit is not being selected:

      // Test.scala
      class A
      class B extends A
       
      trait Y {
        def value: String
      } 
       
      trait X[-T] { // if I make X invariant, this works
        def y(t: T): Y
      }
       
      object XA extends X[A] {
        def y(a: A) = new Y { def value = a.getClass + ": AValue" }
      }
       
      object XB extends X[B] {
        def y(b: B) = new Y { def value = b.getClass + ": BValue" }
      }
       
      object Test {
        implicit def f[T](t: T)(implicit x: X[T]): Y = x.y(t)
        implicit val xa: X[A] = XA
        implicit val xb: X[B] = XB
       
        def main(argv: Array[String]) {
          val a = new A
          val b = new B
          println("A: " + a.value)
          println("B: " + b.value)
        }
      }

      gives:

      $$ scala Test
      A: class A: AValue
      B: class B: AValue

      Making X invariant in T gives a correct result, but of course is much less flexible.

        Attachments

          Activity

            People

            • Assignee:
              milessabin Miles Sabin
              Reporter:
              nuttycom Kris Nuttycombe
              TracCC:
              Edward Kmett, Eric Torreborre, Jason Zaugg
            • Votes:
              2 Vote for this issue
              Watchers:
              12 Start watching this issue

              Dates

              • Created:
                Updated: