补充细节
This commit is contained in:
@@ -1,7 +1,9 @@
|
||||
# Kotlin Springboot
|
||||
# 尝试 Kotlin Springboot
|
||||
|
||||
> 总体上来讲,Kotlin 与 Java 相比是有好有坏的,优点是写起来更简洁,缺点是写起来更简洁。
|
||||
|
||||
## 创建一个 Springboot 项目
|
||||
|
||||
这很简单,在 IDEA 中就可以创建,记得选 Kotlin 和 Gradle kts。
|
||||
这很简单,在 IDEA 中就可以创建,记得选 Kotlin 和 Gradle kts。
|
||||
|
||||
自带插件的话根据你的需要来选就好,如果你只是想利用 Springboot 来做一个命令行小程序也是可以的。
|
||||
@@ -210,6 +210,33 @@ class Dog(override val name: String) : Animal() {
|
||||
}
|
||||
```
|
||||
|
||||
#### 密封
|
||||
|
||||
密封类 / 接口是指在定义的时候前面加上了 `sealed` 关键字。
|
||||
|
||||
- 受限继承:密封类的子类是有限的。所有的直接子类都必须在与密封类相同的文件中声明。
|
||||
- 自身是抽象的:sealed 类本身是抽象的,不能直接被实例化。其构造器默认是 protected 级别。
|
||||
- **配合 when 表达式绝佳**:在 when 语句中使用密封类时,如果处理了所有可能的子类情况,就不需要再写 else 分支。如果以后添加了新子类,编译器会给出提示。
|
||||
|
||||
例如:
|
||||
|
||||
```kotlin
|
||||
sealed class Result<out T> {
|
||||
data class Success<T>(val data: T) : Result<T>()
|
||||
data class Error(val exception: Throwable) : Result<Nothing>()
|
||||
object Loading : Result<Nothing>()
|
||||
}
|
||||
|
||||
// 使用 when 进行处理(无需 else 分支)
|
||||
fun handleResult(result: Result<String>) {
|
||||
when (result) {
|
||||
is Result.Success -> println("成功: ${result.data}")
|
||||
is Result.Error -> println("失败: ${result.message}")
|
||||
Result.Loading -> println("加载中...")
|
||||
} // 单例判断不加 is
|
||||
}
|
||||
```
|
||||
|
||||
### 泛型类
|
||||
|
||||
泛型类把类型作为参数:
|
||||
|
||||
Reference in New Issue
Block a user