密封型参数 [英] Sealed type parameter

查看:34
本文介绍了密封型参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以使用 Scala 宏来生成与以下内容等效的内容:

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 => ???
}

查看 PatternMatching.scala,看起来有一种方法可以将这些约束传达给类型检查器.

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

推荐答案

type Bar <: Foo 定义了一个抽象类型成员,给它具体的定义是完全合法的type Bar = Foo,在这种情况下,匹配将是详尽的.编译器需要匹配的代码和为 Bar 提供具体定义的代码来比较以确定匹配是否详尽.因为这些可能在单独的类/特征中,彼此单独编译,这是不可能的.假设一个超类有抽象定义并编译,然后编译一个具有具体定义的子类,然后在超类中添加match语句并编译.编译器在编译超类的新定义时并不知道子类是否存在,因此无法知道匹配是否是详尽无遗的.

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.

这篇关于密封型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆