kotlin密封类

In this tutorial, we’ll be looking into Kotlin Sealed Class. What are they? What’s their use? We’ll be addressing all of these things below.

在本教程中,我们将研究Kotlin Sealed Class。 这些是什么? 它们有什么用? 我们将在下面解决所有这些问题。

Kotlin密封级 (Kotlin Sealed Class)

In layman terms, as the name suggests, sealed classes are sealed or closed, hence making them restricted.
Sealed classes are used for representing restricted class hierarchies wherein the object or the value can have value only among one of the types, thus fixing your type hierarchies.
Sealed classes are commonly used in cases, where you know what a given value to be only among a given set of options.

用外行人的名字命名,密封类是密封的或封闭的,因此受到限制。
密封类用于表示受限的类层次结构,其中对象或值只能在一种类型中具有值,从而固定了您的类型层次结构。
当您知道给定值仅在给定的一组选项中具有什么值时,通常使用密封类。

实施Kotlin密封课程 (Implementing Kotlin Sealed Classes)

Sealed classes in Kotlin are implemented in the following manner.

Kotlin中的密封类以以下方式实现。

sealed class A{class B : A()class C : A()
}

To specify a sealed class, you need to add the modifier sealed.
A sealed class cannot be instantiated. Hence, are implicitly abstract.
The following WON’T work.

要指定密封类,您需要添加修饰符sealed
密封的类无法实例化。 因此,是隐式的抽象。
以下将不起作用。

fun main(args: Array<String>)
{var a = A() //compiler error. Class A cannot be instantiated.
}

Constructors of a sealed class are private by default.
All subclasses of a sealed class must be declared within the same file.
Sealed classes are important in ensuring type safety by restricting the set of types at compile-time only.

默认情况下,密封类的构造函数是私有的。
密封类的所有子类必须在同一文件中声明。
密封类对于仅通过在编译时限制类型集来确保类型安全非常重要。

sealed class A{class B : A() {class E : A() //this works.}class C : A()init {println("sealed class A")}}class D : A() //this works
{
class F: A() //This won't work. Since sealed class is defined in another scope.
}

Creating a sealed class with constructors.

用构造函数创建一个密封的类。

sealed class A(var name: String){class B : A("B")class C : A("C")
}class D : A("D")
fun main(args: Array<String>) {var b = A.B()var d = D()
}

Adding Data Class and Object in a sealed class.

在密封的类中添加数据类和对象 。

fun main(args: Array<String>) {val e = A.E("Anupam")println(e) //prints E(name=Anupam)var d = A.Dd.name() //prints Object D
}sealed class A{class B : A()class C : A()object D : A(){fun name(){println("Object D")}}data class E(var name: String) : A()}

枚举和密封类之间的区别 (Difference between enum and sealed classes)

In Kotlin, Sealed Classes can be termed as Enum classes on steroids.
Sealed classes allow us to create instances with different types, unlike Enums which restrict us to use the same type for all enum constants.
The following isn’t possible in Enum classes.

在Kotlin中,密封类可以称为类固醇的Enum类。
密封类允许我们创建具有不同类型的实例,这与枚举不同, 枚举将我们限制为所有枚举常量使用相同的类型。
在Enum类中不可能执行以下操作。

enum class Months(string: String){
January("Jan"), February(2),
}

Enum classes allow only a single type for all constants.
Here’s where sealed classes come to our rescue by allowing multiple instances.

枚举类仅允许所有常量使用单一类型。
在这里,密封类通过允许多个实例来拯救我们。

sealed class Months {class January(var shortHand: String) : Months()class February(var number: Int) : Months()class March(var shortHand: String, var number: Int) : Months()
}

How can you use this feature of Sealed classes in your Projects?
In a newsfeed like application, you can create three different class types for Status, Image, Video posts as shown below.

如何在项目中使用Sealed类的此功能?
在类似新闻源的应用程序中,您可以为状态,图像和视频帖子创建三种不同的类类型,如下所示。

sealed class Post
{class Status(var text: String) : Post()class Image(var url: String, var caption: String) : Post()class Video(var url: String, var timeDuration: Int, var encoding: String): Post()
}

This isn’t possible with Enum classes.

使用Enum类是不可能的。

密封班和何时 (Sealed classes and when)

Sealed classes are commonly used with when statements since each of the subclasses and their types act as a case. Moreover, we know that the Sealed class limits the types. Hence, the else part of the when statement can be easily removed.
Following example demonstrates the same.

密封类通常与when语句一起使用,因为每个子类及其类型都作为个案。 此外,我们知道Sealed类会限制类型。 因此, when语句的else部分可以轻松删除。
下面的示例演示了相同的内容。

sealed class Shape{class Circle(var radius: Float): Shape()class Square(var length: Int): Shape()class Rectangle(var length: Int, var breadth: Int): Shape()
}fun eval(e: Shape) =when (e) {is Shape.Circle -> println("Circle area is ${3.14*e.radius*e.radius}")is Shape.Square -> println("Square area is ${e.length*e.length}")is Shape.Rectangle -> println("Rectagle area is ${e.length*e.breadth}")}

Let’s execute the eval function in our main function as shown below.

让我们在main函数中执行eval函数,如下所示。

fun main(args: Array<String>) {var circle = Shape.Circle(4.5f)var square = Shape.Square(4)var rectangle = Shape.Rectangle(4,5)eval(circle)eval(square)eval(rectangle)//eval(x) //compile-time error.}//Following is printed on the console:
//Circle area is 63.585
//Square area is 16
//Rectangle area is 20

Note: The is modifier checks if the class is of the following type.
is modifier is required only for classes. Not with Kotlin objects as shown below:

注意: is修饰符检查类是否为以下类型。
is修饰符仅对于类是必需的。 不适用于Kotlin对象,如下所示:

sealed class Shape{class Circle(var radius: Float): Shape()class Square(var length: Int): Shape()object Rectangle: Shape(){var length: Int = 0var breadth : Int = 0}
}fun eval(e: Shape) =when (e) {is Shape.Circle -> println("Circle area is ${3.14*e.radius*e.radius}")is Shape.Square -> println("Square area is ${e.length*e.length}")Shape.Rectangle -> println("Rectangle area is ${Shape.Rectangle.length*Shape.Rectangle.breadth}")}

This brings an end to kotlin sealed class tutorial.

这样就结束了kotlin密封类教程。

References: Kotlin Docs

参考: Kotlin Docs

翻译自: https://www.journaldev.com/18719/kotlin-sealed-class

kotlin密封类

kotlin密封类_Kotlin密封级相关推荐

  1. 理解Kotlin密封类Sealed

    " 密封类和接口表示受限制的类层次结构,提供对继承的更多控制.密封类的所有直接子类在编译时都是已知的.在定义密封类的模块和包之外不能出现其他子类.例如,第三方客户端不能在其代码中扩展您的密封 ...

  2. C#学习笔记——密封类与密封方法

    密封类可以用来限制扩展性,如果密封了某个类,则其他类不可以从该类继承:如果密封了某个成员,则派生类不能重写该成员的实现.默认情况下,不应密封类型和成员.密封可以防止对库的类型和成员进行自定义,但也影响 ...

  3. kotlin泛型_Kotlin泛型

    kotlin泛型 In this tutorial, we'll be looking in Kotlin Generics and Variances. 在本教程中,我们将研究Kotlin的泛型和变 ...

  4. Kotlin 密封类代替枚举类

    密封类代替枚举类 在Kotlin中由于密封类的特性,所以可以完全取代枚举类 应为object是final类,所以不能继承普通类,但是密封类是abstract,所以可以继承 示例中使用了中缀符号infi ...

  5. kotlin 构造函数_Kotlin程序| 主要构造函数示例

    kotlin 构造函数 主要建设者 (Primary Constructor) A Kotlin class have Primary constructor and one or more Seco ...

  6. kotlin 二进制_Kotlin程序检查数字是否为二进制

    kotlin 二进制 Given a number, we have to check whether given number is a binary or not. 给定一个数字,我们必须检查给定 ...

  7. kotlin编程语言_Kotlin初学者编程基础

    kotlin编程语言 什么是Kotlin? (What is Kotlin?) Kotlin is a programming language developed by Jetbrains, the ...

  8. kotlin 字符串_Kotlin程序确定字符串是否具有所有唯一字符

    kotlin 字符串 Given a string, we have to check whether it has all unique characters or not. 给定一个字符串,我们必 ...

  9. [转载] kotlin 字符串_Kotlin基本类型字符串

    参考链接: Python字符串串联Concatenation kotlin 字符串 Kotlin has five basic data types. In a previous post, we d ...

最新文章

  1. Go 学习笔记(82)— Go 第三方库之 viper(解析配置文件、热更新配置文件)
  2. python程序实例电话本-Python示例
  3. 【Python】学习笔记一:Hello world
  4. SET key value [EX seconds] [PX milliseconds] [NX|XX]
  5. php Heredoc应用说明
  6. UE4从4.15移植到4.16
  7. 在视觉任务上大幅超越ReLU的新型激活函数
  8. 二倍图三倍图什么意思_为什么说我们需要软件架构图?
  9. OpenCV-计时函数cv::getTickCountcv::getTickFrequency
  10. mapreduce task与spark task对比
  11. 批量修改文件夹名称的一部分
  12. spring boot 核心配置文件是什么?
  13. (2) python--pandas
  14. 霍尔 磁电 光电式传感器的比较 实验思考题
  15. 使用fiddler实现手机抓包
  16. 今日立春,介绍一些立春的习俗吧
  17. 为什么高水平程序员不喜欢接外包项目
  18. 近期微信登录10005报错,解决办法
  19. 【数据库】oracle数据库当中的dual表是个什么东西?
  20. 网页防篡改技术的前世与今生

热门文章

  1. 笔记(2015.8.1)
  2. 闲来无事写写-Huffman树的生成过程
  3. hdu 1261 字串数
  4. Membership、MembershipUser和Roles类
  5. [转载] TensorFlow2.0 学习 线性回归
  6. [转载] Python字典按照keys排序输出为列表
  7. [转载] 【Python】set() 集合操作与运算 元素输出顺序
  8. [转载] Pytorch入门实战-----逻辑回归识别手写数据集
  9. [转载] java构造函数初始化与执行顺序问题
  10. python 基础课程第三天