scala sealed trait

来源:互联网 发布:支持spi的读卡器淘宝 编辑:程序博客网 时间:2024/05/18 08:15

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 Answercase object Yes extends Answercase object No extends Answer

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

scala> val x: Answer = Yesx: Answer = Yesscala> 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 atlist and option implementations.

0 0
原创粉丝点击