- Learn Kotlin Programming(Second Edition)
- Stephen Samuel Stefan Bocutiu
- 324字
- 2021-06-24 14:13:34
Sealed classes
A sealed class in Kotlin is an abstract class, which can be extended by subclasses defined as nested classes within the sealed class itself. In a way, this is a rather more powerful enumeration option. Just like Enum, a sealed class hierarchy contains a fixed set of possible choices. However, unlike Enum, where each option is represented by one instance, the derived classes of a sealed class can have many instances. Sealed classes are ideal for defining algebraic data types. Imagine you want to model a binary tree structure and you do the following:
sealed class IntBinaryTree { class EmptyNode : IntBinaryTree() class IntBinaryTreeNode(val left: IntBinaryTree, val value: Int, val right: IntBinaryTree) : IntBinaryTree() } … val tree = IntBinaryTree.IntBinaryTreeNode( IntBinaryTree.IntBinaryTreeNode( IntBinaryTree.EmptyNode(), 1, IntBinaryTree.EmptyNode()), 10, IntBinaryTree.EmptyNode())
Ideally, you won't hardcode the container value to be an integer, but make it generic in order to hold any type. But since we haven't introduced generics yet, we keep things a little bit simpler. In the preceding snippet, you may have noticed the presence of the sealed keyword. Trying to define a derived class outside the IntBinaryTree class scope will yield a compilation error.
The benefits of using such a class hierarchy come into play when you use them in a when expression. The compiler is able to infer a statement and cover all the possible cases; therefore, the check is exhaustive. For a Scala developer, this will sound familiar to pattern matching. Imagine we want to expose the elements of a tree to a list; for this, you would do the following:
fun toCollection(tree: IntBinaryTree): Collection<Int> = when (tree) { is IntBinaryTree.EmptyNode -> emptyList<Int>() is IntBinaryTree.IntBinaryTreeNode -> toCollection(tree.left) + tree.value + toCollection(tree.right) }
If you leave one of the derived classes out of the when expression, you will get a compiler error as follows:
Error:(12, 5) Kotlin: 'when' expression must be exhaustive, add necessary 'is EmptyNode' branch or 'else' branch instead
- Implementing VMware Horizon 7(Second Edition)
- Highcharts Cookbook
- Protocol-Oriented Programming with Swift
- ScratchJr趣味編程動手玩:讓孩子用編程講故事
- Node學習指南(第2版)
- Instant jQuery Boilerplate for Plugins
- Scala Functional Programming Patterns
- 人人都能開發(fā)RPA機器人:UiPath從入門到實戰(zhàn)
- Java EE項目應(yīng)用開發(fā)
- 分布式數(shù)據(jù)庫HBase案例教程
- HTML5 Canvas核心技術(shù):圖形、動畫與游戲開發(fā)
- 零基礎(chǔ)C語言學習筆記
- Learning Ext JS(Fourth Edition)
- Building an E-Commerce Application with MEAN
- Mastering Rust