Sealed Class Hierarchies

来源:互联网 发布:淘宝低价销售的危害 编辑:程序博客网 时间:2024/05/22 02:19

A key point about Option is that there are really only two valid subtypes. Either we have a value, the Some case, or we don’t, the None case. There are no other subtypes of Option that would be valid. So, we would really like to prevent users from creating their own.

Scala has a keyword sealed for this purpose. Option is declared like this (eliding some details):

sealed abstract class Option[+A] ... { ... }

The sealed keyword tells the compiler that all subclasses must be declared in the same source file. Some and None are declared in the same file with Option in the Scala library. This technique effectively prevents additional subtypes of Option.


Ref

《Programming Scala》

0 0
原创粉丝点击