kotlin - 将密封类声明为对象的好处

标签 kotlin sealed-class

上下文

我有这个密封类和它的每一个子类:

sealed class Section

class SearchSection : Section()
class FavoritesSection : Section()
class RecommendationsSection : Section()
class ProfileSection : Section()

但我在每个类声明中都会收到警告:

Sealed sub-classhas no state and no overrite equals

这建议我将它们声明为:

object ProfileSection : Section()

问题

  • 这样做的目的是什么?
  • 有什么好处?
  • 为什么我要把它们写成 object 而不是 class

最佳答案

首先让我解释一下密封类的目的是什么。 the official documentation 中的第一句话说:

Sealed classes are used for representing restricted class hierarchies, when a value can have one of the types from a limited set, but cannot have any other type. They are, in a sense, an extension of enum classes.

我相信您已经熟悉枚举,它们是一种特殊类型,可以将变量定义为预定义常量之一,并且每个都可以存储一些额外的数据。每个常数只有一个实例。至此,您可能已经注意到这个单一实例和数据保存的东西听起来像 Kotlin 对象。所以原来这个枚举类:

enum class Type(val value: String) {
    A("a"),
    B("b")
}

等价于这个密封类:

sealed class Type(val value: String) {
    object A : Type("a")
    object B : Type("b")
}

(实际上枚举常量是 Kotlin 中的对象)。

密封类的特别之处在于它们允许您使用类而不是对象来定义“常量”,因此它们可以拥有多个实例并因此存储实际状态,例如:

sealed class ApiReponse

data class Success(val data: Data) : ApiResponse()
object Error : ApiResponse()

fun getResponse(): ApiResponse {
    ...
    return if (apiCall.isSuccessful) Success(apiCall.data) else Error
}

所以最后回答你原来的问题:

What is the purpose of this?

与枚举常量相同。如果您不需要在“常量”中存储状态并且只需要带有可选静态数据的命名类型,那么请使用对象。

What are the benefits?

Why I should write them as object and not a class?

如果你不需要你的“常量”来拥有一个状态,那么每次你想使用它时创建一个不同的实例只是浪费内存。

关于kotlin - 将密封类声明为对象的好处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59440125/

相关文章:

null - 在 Kotlin catch block 中设置一个 val

android - 在新的 Android Studio 3.1 上构建时出错

Kotlin 在 Jackson 中密封了类子类型

kotlin - 当抽象类的构造函数在 kotlin 中是私有(private)的时会发生什么?

android - 在 Activity 的 init block 中使用 'this' 作为上下文?

android - LiveData 观察者的 Kotlin 语法?

ios - Kotlin 多平台 (KMM) 中是否有 AES 128 加密(密码)逻辑?

java - 如何以及何时在 Java 中使用 Kotlin 密封类?

android - 如何在包中将数据类作为 Parcelable 传递?

java - 无法在 java 中使用 ObjectInputStream 和 SealedObject 来使用 readObject()。获取运行时错误