bug icon indicating copy to clipboard operation
bug copied to clipboard

Match on inner type generates no compiler warning but fails at runtime

Open scabug opened this issue 10 years ago • 3 comments

The attached sample code compiles fine in Scala 2.11.7 and Scala 2.10.3 (Scala 2.9.3 warns that "TestMain.scala:9: error: scrutinee is incompatible with pattern type") - even with -unchecked -deprecation -feature -Xfuture -Xfatal-warnings -Xlint compiler options - but prints "ChildA#InnerOne: b.InnerOne" when run, i.e. the match at TestMain:8 matches ChildA#InnerOne although x is ChildB#InnerOne (and thus I'd expect it to print "ChildB#InnerOne: b.InnerOne". While I think the match should be possible (by type-checking the reference to the outer object) the compiler should at least generate a warning (like it does for matching things like case e:Seq[String]=> ???.

scabug avatar Sep 23 '15 09:09 scabug

Imported From: https://issues.scala-lang.org/browse/SI-9484?orig=1 Reporter: Bernhard Messerer (messi) Affected Versions: 2.11.7 See #2, #6583 Attachments:

scabug avatar Sep 23 '15 09:09 scabug

@som-snytt said: Similar search terms might lead one to #2.

scabug avatar Sep 24 '15 04:09 scabug

At 2.13.8, still no outer checking, but compiler overcompensates by warning:

t9484.scala:9: warning: match may not be exhaustive.
It would fail on the following input: (x: Parent#InnerOne forSome x not in (ChildA#InnerOne, ChildB#InnerOne))
    x match {
    ^

The attached test

object TestMain {
  def main(args:Array[String]): Unit = {
    val b=new ChildB
    val x:Parent#InnerOne=new b.InnerOne("b.InnerOne")
    matchInnerOne(x)
  }
  def matchInnerOne(x:Parent#InnerOne):Unit={
    x match {
      case ao:ChildA#InnerOne⇒ println("ChildA#InnerOne: "+ao.name)
      case bo:ChildB#InnerOne⇒ println("ChildB#InnerOne: "+bo.name)
    }
  }
}

sealed trait Parent {
  sealed trait Inner {
    def name:String
  }
  final class InnerOne(val name:String) extends Inner
  final class InnerTwo(val name:String) extends Inner
}
class ChildA extends Parent
class ChildB extends Parent

Oh wait, ChildX are not final. OK, same result if final.

som-snytt avatar Mar 09 '22 18:03 som-snytt

anyone digging into this will probably also want to read #4440

SethTisue avatar Mar 24 '23 13:03 SethTisue

Scala 3 (3.3.1-RC1-bin-20230323-ee2bfdb-NIGHTLY) doesn't even warn

SethTisue avatar Mar 24 '23 13:03 SethTisue