官术网_书友最值得收藏!

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
主站蜘蛛池模板: 嵊州市| 临洮县| 德保县| 集安市| 枣阳市| 灵璧县| 宁波市| 江阴市| 龙南县| 逊克县| 峡江县| 蛟河市| 伊金霍洛旗| 浦江县| 永登县| 宝丰县| 泾川县| 凤凰县| 陈巴尔虎旗| 定兴县| 钦州市| 张掖市| 贡觉县| 垦利县| 鹿邑县| 谢通门县| 禹州市| 沾益县| 崇礼县| 防城港市| 定襄县| 福安市| 达日县| 溧阳市| 禄丰县| 专栏| 庆安县| 荔波县| 山西省| 南汇区| 海安县|