bug icon indicating copy to clipboard operation
bug copied to clipboard

Pattern matching & existential type members

Open scabug opened this issue 9 years ago • 3 comments

The following snippet doesn't compile, but should.

sealed trait Outer {
  type Inner
}

case object HasInts extends Outer {
  override type Inner = Int
}

def id(outer: Outer): outer.Inner =
  outer match {
    case HasInts => 0
  }

So long as the case's #Inner is final (in this case it is because HasInts is final), that should be proof that outer.Inner == the case's #Inner.

I'd expect the above code to work in the same way, and for the same results, as the below code which compiles successfully.

    sealed trait Outer[Inner]

    case object HasInts extends Outer[Int]

    def id[I](outer: Outer[I]): I =
      outer match {
        case HasInts => 0
      }

scabug avatar Apr 25 '16 08:04 scabug

Imported From: https://issues.scala-lang.org/browse/SI-9765?orig=1 Reporter: David Barri (japgolly) Affected Versions: 2.11.8

scabug avatar Apr 25 '16 08:04 scabug

@paulp said: case HasInts => uses value equality so you shouldn't expect that to work. It might be HasInts, or it could be anything which compares equal to HasInts. But case _: HasInts.type => doesn't work either, and probably that one should.

Of course, just because you shouldn't expect it to work doesn't mean it doesn't.

sealed trait Outer[Inner]
case object HasInts extends Outer[Int] {
  override def equals(x: Any) = true
}

object Test {
  def id[I](outer: Outer[I]): I = outer match {
    case HasInts => 0
    case _       => ???
  }
  def main(args: Array[String]): Unit = {
    val os = new Outer[String] {}
    var x = ""
    x = id(os)
  }
}
// % scalac212 a.scala && scala212 Test
// java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
//   at Test$.main(a.scala:14)
//   at Test.main(a.scala)

scabug avatar Apr 27 '16 23:04 scabug

neither version of the code works in Scala 3, either. in any case, this is virtually certain to be out of scope in Scala 2

SethTisue avatar Mar 09 '25 16:03 SethTisue