Sealed type parameter

南笙酒味 提交于 2020-01-05 12:12:13

问题


I was wondering if it would be possible to use Scala macros to generate something equivalent to the following:

sealed type Foo
type Bar <: Foo
type Baz <: Foo

Then the following expression would be recognized as not being exhaustive

(foo: Foo) match {
  case bar: Bar => ???
}

Looking at the comments in PatternMatching.scala, it looks like there could be a way to communicate those constraints to the typechecker.


回答1:


type Bar <: Foo defines an abstract type member, it would be perfectly legal for it to be given the concrete definition type Bar = Foo, in which case the match would be exhaustive. The compiler would need the code for the match and the code giving the concrete definition to Bar to compare to decide if the match was exhaustive. Because these could be in separate classes/traits, compiled separately from each other, this is not possible. Suppose a superclass has the abstract definition and is compiled, then a subclass with the concrete definition is compiled, then the match statement is added in the superclass and compiled. The compiler has no idea that the subclass exists when compiling the new definition of the superclass, so it has no way of knowing that the match isn't exhaustive.



来源:https://stackoverflow.com/questions/23925763/sealed-type-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!