From 460d09a5920e75b224b5a212e7b7c6c2d382acd1 Mon Sep 17 00:00:00 2001 From: SOR <3272194354@qq.com> Date: Wed, 23 Sep 2026 11:27:33 +0800 Subject: [PATCH] =?UTF-8?q?=E8=A1=A5=E5=85=85=E7=BB=86=E8=8A=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Learning/Kotlin-Springboot.md | 6 ++++-- Learning/深入Kotlin.md | 27 +++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/Learning/Kotlin-Springboot.md b/Learning/Kotlin-Springboot.md index fb353df..18d0b78 100644 --- a/Learning/Kotlin-Springboot.md +++ b/Learning/Kotlin-Springboot.md @@ -1,7 +1,9 @@ -# Kotlin Springboot +# 尝试 Kotlin Springboot > 总体上来讲,Kotlin 与 Java 相比是有好有坏的,优点是写起来更简洁,缺点是写起来更简洁。 ## 创建一个 Springboot 项目 -这很简单,在 IDEA 中就可以创建,记得选 Kotlin 和 Gradle kts。 \ No newline at end of file +这很简单,在 IDEA 中就可以创建,记得选 Kotlin 和 Gradle kts。 + +自带插件的话根据你的需要来选就好,如果你只是想利用 Springboot 来做一个命令行小程序也是可以的。 \ No newline at end of file diff --git a/Learning/深入Kotlin.md b/Learning/深入Kotlin.md index 6a2963a..0b8bf3b 100644 --- a/Learning/深入Kotlin.md +++ b/Learning/深入Kotlin.md @@ -210,6 +210,33 @@ class Dog(override val name: String) : Animal() { } ``` +#### 密封 + +密封类 / 接口是指在定义的时候前面加上了 `sealed` 关键字。 + +- 受限继承:密封类的子类是有限的。所有的直接子类都必须在与密封类相同的文件中声明。 +- 自身是抽象的:sealed 类本身是抽象的,不能直接被实例化。其构造器默认是 protected 级别。 +- **配合 when 表达式绝佳**:在 when 语句中使用密封类时,如果处理了所有可能的子类情况,就不需要再写 else 分支。如果以后添加了新子类,编译器会给出提示。 + +例如: + +```kotlin +sealed class Result { + data class Success(val data: T) : Result() + data class Error(val exception: Throwable) : Result() + object Loading : Result() +} + +// 使用 when 进行处理(无需 else 分支) +fun handleResult(result: Result) { + when (result) { + is Result.Success -> println("成功: ${result.data}") + is Result.Error -> println("失败: ${result.message}") + Result.Loading -> println("加载中...") + } // 单例判断不加 is +} +``` + ### 泛型类 泛型类把类型作为参数: