lampepfl / dotty-feature-requests

Historical feature requests. Please create new feature requests at https://github.com/lampepfl/dotty/discussions/new?category=feature-requests
31 stars 2 forks source link

Pattern match should know a Set can't be a List because List is sealed and children are final #16

Open Blaisorblade opened 6 years ago

Blaisorblade commented 6 years ago

Reported on Gitter by @ekrich. People often complain that you can match an A against an unrelated B — say, a Set against List. In most cases they're wrong (tho it's sometimes unfortunate), but for Set and List they seem to be right, because List is sealed and none of its descendents can be extended. Scalac gives no warning for this either. /cc @liufengyun

scala> def s(it: Set[Int]) = it match { case _ : List[_] => "match"; case _ => "fail" }
def s(it: Set[Int]): String
scala> s(new List[Int] with Set[Int] {})
1 |s(new List[Int] with Set[Int] {})
  |   ^
  |   Cannot extend sealed class List in a different source file
scala> s(new ::[Int](1, Nil) with Set[Int] {})
1 |s(new ::[Int](1, Nil) with Set[Int] {})
  |  ^
  |  anonymous class ::[Int] with Set[Int]{...} cannot extend final class ::
liufengyun commented 5 years ago

The semantics of sealed is related to compilation-unit. It implies to take advantage of the knowledge that a sealed class cannot be extended outside of its compilation unit, the subtyping checker has to be compilation-unit aware, which seems difficult to implement.