什么是密封性状? [英] What is a sealed trait?

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

问题描述

"Scala编程"中描述了密封类,但没有密封特征. 在哪里可以找到有关密封性状的更多信息?

我想知道,密封特征是否与密封类相同? 或者,如果没有,有什么区别? 什么时候使用密封特性(什么时候不使用)是一个好主意?

解决方案

sealed特性只能在与其声明相同的文件中扩展.

它们通常用于提供enums的替代方法.由于它们只能在单个文件中扩展,因此编译器知道每种可能的子类型并可以对此进行推理.

例如声明:

sealed trait Answer
case object Yes extends Answer
case object No extends Answer

如果匹配不详尽,编译器将发出警告:

scala> val x: Answer = Yes
x: Answer = Yes

scala> x match {
     |   case No => println("No")
     | }
<console>:12: warning: match is not exhaustive!
missing combination            Yes

因此,如果可能的子类型的数量是有限的并且事先已知,则应该使用密封的特征(或密封的抽象类).有关更多示例,请查看列表选项实现. >

Sealed classes are described in 'Programming in Scala', but sealed traits are not. Where can I find more information about a sealed trait?

I would like to know, if a sealed trait is the same as a sealed class? Or, if not, what are the differences? When is it a good idea to use a sealed trait (and when not)?

解决方案

A sealed trait can be extended only in the same file as its declaration.

They are often used to provide an alternative to enums. Since they can be only extended in a single file, the compiler knows every possible subtypes and can reason about it.

For instance with the declaration:

sealed trait Answer
case object Yes extends Answer
case object No extends Answer

The compiler will emit a warning if a match is not exhaustive:

scala> val x: Answer = Yes
x: Answer = Yes

scala> x match {
     |   case No => println("No")
     | }
<console>:12: warning: match is not exhaustive!
missing combination            Yes

So you should use sealed traits (or sealed abstract class) if the number of possible subtypes is finite and known in advance. For more examples you can have a look at list and option implementations.

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

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