今天我遇到了 科特林密封级 我以前从未听说过。经过研究,我发现这个概念并不是什么新鲜事物,例如在Scala中也可以使用。那么,还有另一个Scala功能JetBrains被认为相关且适合Kotlin吗?我喜欢那个ðŸ™,阅读这篇 发布 如果您对Kotlin的更多功能感兴趣。
实际上,这是一个非常简单的功能,我将在下面进行解释。
Kotlin密封等级-功能说明
A sealed
class can be subclassed and may include abstract
methods, which means that sealed
classes are abstract
 implicitly, although the documentation doesn't clearly say so. To actually make a class "sealed" we have to put the sealed
modifier before its name, as we can see here:
sealed class MyClass
限制
的 重要 关于密封类的事情是 子类必须与密封类在同一文件中声明 本身。
效益
该功能使我们可以定义类 层次结构 那是 受类型限制,即子类。由于所有子类都需要在密封类的文件中定义,因此不会出现编译器不知道的未知子类。
Wait... Isn't this what an enum
 actually is?
Kotlin密封类是普通枚举的某种扩展:与枚举相反,密封类的子类可以是 实例化多次 并且实际上可以包含 州.
用例
的 main advantage of sealed classes reveals itself if it's used in when
expressions. Let's compare a normal class hierarchy to one of a sealed class handled in a when
. First, we'll create a hierarchy of Mammal
s and then put it in a method with a when
:
open class Mammal(val name: String)
class Cat(val catName: String) : Mammal(catName)
class Human(val humanName: String, val job: String) : Mammal(humanName)
fun greetMammal(mammal: Mammal): String {
when (mammal) {
is Human -> return "Hello ${mammal.name}; You're working as a ${mammal.job}"
is Cat -> return "Hello ${mammal.name}"
else -> return "Hello unknown"
}
}
的 else
is mandatory, otherwise, the compiler will complain. This is because it just cannot verify that all possible cases, i.e. subclasses, are covered here. It may be possible that a subclass Dog
is available at any time which is unknown at compile time.
封印为“营救”
But what if we knew there wouldn't be other Mammal
s in our application? We'd want to leave out the elseÂ
block.
的 problem of unknown subclasses can be avoided 通过 sealed classes. Let's modify the base class Mammal
, its' subclasses can remain the same.
sealed class Mammal(val name: String)
Now we can simply omit the else
clause since the compiler 可以验证 that all possible cases are covered because only the subclasses in the file of the sealed
class exist, without exception. 的 method now looks as follows:
fun greetMammal(mammal: Mammal): String {
when (mammal) {
is Human -> return "Hello ${mammal.name}; You're working as a ${mammal.job}"
is Cat -> return "Hello ${mammal.name}"
// `else` clause not required, all the cases covered
}
}
而已。总之真的很方便,不是吗?自己尝试玩吧!
最后,如果您想更详细地了解Kotlin中的密封课程,我推荐这本书 行动中的科特林 给你!
西蒙
西蒙是总部位于德国的软件工程师,具有7年为JVM和JavaScript编写代码的经验。他’他对尽可能多地学习新事物充满热情,并且是科特林(Kotlin)的自发狂热者。