scala / bug

Scala 2 bug reports only. Please, no questions — proper bug reports only.
https://scala-lang.org
230 stars 21 forks source link

Invalid "Pattern type is incompatible with expected type" #9837

Open scabug opened 8 years ago

scabug commented 8 years ago

The compiler rejects code which should be perfectly valid. Using type ascription to upcast the value is a workaround for this.

sealed trait Key
case object SilverKey extends Key
case object GoldKey extends Key

trait KeyHole {
  type K <: Key
}

trait Door {
  val h: KeyHole
  type K = Key with h.K
  val key: K
}

// pattern type is incompatible with expected type
def bad(door: Door): Unit = {
  door.key match {
    case SilverKey =>
    case GoldKey =>
  }
}

// compiles fine
def good(door: Door): Unit = {
  (door.key: Key) match {
    case SilverKey =>
    case GoldKey =>
  }
}
scabug commented 8 years ago

Imported From: https://issues.scala-lang.org/browse/SI-9837?orig=1 Reporter: Cary Robbins (carymrobbins) See #6130

scabug commented 7 years ago

@SethTisue said: Note that the indirection through the type alias Door.K is not a factor here; the error message is the same if you take that out and just write val key: Key with h.K.

I haven't studied both tickets closely, but #6130 looks loosely related (but there is no extractor here, so this one seems more fundamental).

scabug commented 7 years ago

@som-snytt said: Why is the error invalid? SilverKey does not conform to some arbitrary door.key, where door.h.Key might be my SpecialSkeletonKey.

The conformance test says, We'll match if SilverKey.equals(a SpecialSkeletonKey), so SilverKey must be competent to make that test.

I think the error is for objects what "constructor cannot be instantiated to expected type" is for case classes?

It's not obvious to me that the upper bound on K means we intend to match on any old Key.

SethTisue commented 5 years ago

Dotty accepts this code.

SethTisue commented 5 years ago

@som-snytt it seems to me that the compiler doesn't have to prove that it can match, it must accept the code unless it can prove it can't match