Skip to content

Pattern matching on sealed abstract classes causes spurious warning #3145

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Jacoby6000 opened this issue Sep 21, 2017 · 4 comments
Closed

Comments

@Jacoby6000
Copy link

In some situations, matching on a sealed abstract class using a type annotation will cause the compiler to warn about unreachable code

  sealed trait Foo
  class Bar(val s: String) extends Foo
  sealed abstract class Baz(val s: String) extends Foo
  
  val f: Foo => String = { 
    case bar: Bar => bar.s
    case baz: Baz => baz.s
  }

This warning does not happen if the case for the sealed abstract class comes first.

@allanrenucci
Copy link
Contributor

Can be reproduced with sealed trait too:

sealed trait Foo
class Bar extends Foo
sealed trait Baz extends Foo

class Test {
  def f(x: Foo) = x match { 
    case bar: Bar => 1
    case baz: Baz => 2
  }
}

@liufengyun
Copy link
Contributor

This seems to be the intended behaviour, because Baz cannot be instantiated. Scalac 2.12.3 generates the same warning.

@allanrenucci
Copy link
Contributor

What about this example:

sealed trait Foo
class Bar extends Foo
sealed trait Baz extends Foo

class Test {
  def f = {
    val x = new Baz {}
    x match { 
      case bar: Bar => 1
      case baz: Baz => 2
    }
  }
}

scalac emits no warning here.

@liufengyun
Copy link
Contributor

The last example above is due to the problem of anonymous class extending sealed class/trait.

@smarter suggested to simply disallow anonymous class extending sealed class/trait long time ago, see below:

#1917 (comment)

Currently, the exhaustivity check doesn't have the information to know whether a sealed trait has anonymous children or not.

liufengyun added a commit to dotty-staging/dotty that referenced this issue Jan 23, 2018
Sealed classes and traits are effectively inhabited in
practice. By treating them as inhabited by default,
we avoid spurious warnings that ignore anonymous classes.

When we have a mechanism to track anonymous children or
disallow anonymous children for sealed classes, we
could revert this change to make the check stronger.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants