Scala 中的最终类和密封类有什么区别? [英] What are the differences between final class and sealed class in Scala?

查看:59
本文介绍了Scala 中的最终类和密封类有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Scala 中有两种修饰符:finalsealed

它们之间有什么区别?什么时候应该使用一个?

解决方案

final 类不能扩展,句号.

sealed trait 只能在与声明相同的源文件中扩展.这对于创建 ADT(代数数据类型)很有用.ADT 由其派生类型的sum定义.

例如:

  • Option[A]Some[A] + None 定义.
  • A List[A]:: + Nil 定义.
<小时>

密封特性选项[+A]最终案例类 Some[+A] 扩展 Option[A]对象无扩展选项[Nothing]

因为 Option[A] 是密封的,其他开发者无法对其进行扩展 - 这样做会改变其含义.

Some[A] 是最终的,因为它不能被延长,期间.

<小时>

作为一个额外的好处,如果一个特征被密封,如果你的模式匹配不够详尽,编译器会警告你,因为它知道Option限制SomeNone.

选择匹配{case Some(a) =>你好"}

<块引用>

警告:匹配可能并不详尽.它会在以下输入上失败:None

There are two types of modifiers in Scala: final and sealed

What are the differences between them? When should you use one over the other?

解决方案

A final class cannot be extended, period.

A sealed trait can only be extended in the same source file as it's declared. This is useful for creating ADTs (algebraic data types). An ADT is defined by the sum of its derived types.

E.g.:

  • An Option[A] is defined by Some[A] + None.
  • A List[A] is defined by :: + Nil.

sealed trait Option[+A]

final case class Some[+A] extends Option[A]
object None extends Option[Nothing]

Because Option[A] is sealed, it cannot be extended by other developers - doing so would alter its meaning.

Some[A] is final because it cannot be extended, period.


As an added bonus, if a trait is sealed, the compiler can warn you if your pattern matches are not exhaustive enough because it knows that Option is limited to Some and None.

opt match {
    case Some(a) => "hello"
}

Warning: match may not be exhaustive. It would fail on the following input: None

这篇关于Scala 中的最终类和密封类有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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