Common Operations

只需要知道有这些操作 shuffle() vs shuffled() fun main() { val list: MutableList<Int> = mutableListOf(1, 2, 3, 4, 5) val shuffledList = list.shuffled() // shuffled 返回打乱后的集合 println(list) println(shuffledList) list.shuffle() println(list) } map() fun main() { val numbers = listOf(1, 2, 3) val doubled = numbers.map { it * 2 } // [2, 4, 6] val strings = numbers.map { "数字$it" } // ["数字1", "数字2", "数字3"] } toSet() fun main() { val list = listOf(1, 2, 3, 2, 1) val set = list.toSet() println(set) // [1, 2, 3] } sortedDescending() fun main() { val list = listOf(1, 2, 3, 2, 1) val sorted = list.sortedDescending() //降序排列 println(sorted) // [3, 2, 2, 1, 1] } filter() fun main() { val list = listOf(2, 4, 3, 6, 1) val filter = list.filter { it % 2 == 0 } println(filter) // [2, 4, 6] } groupingBy { }.eachCount() fun main() { val words = listOf("apple", "banana", "apple", "cherry", "banana") val counts = words.groupingBy { it }.eachCount() println(counts) // {apple=2, banana=2, cherry=1} } entries() fun main() { val map = mapOf(1 to 2, 3 to 4) map.entries.forEach { (key, value) -> println("$key, $value") } } addAll() fun main() { val list1 = mutableListOf(1, 23, 45, 6) val list2 = listOf(666666, 888888) list1.addAll(list2) println(list1) // [1, 23, 45, 6, 666666, 888888] } buildList { } fun main() { val list = buildList { add(1) add(2) addAll(listOf(3, 4)) } println(list) // [1, 2, 3, 4] } require() - 检查参数 fun divide(a: Int, b: Int): Int { require(b != 0) { "除数不能为 0" } return a / b } check() - 检查当前状态 class BankAccount { private var balance: Int = 0 fun withDraw(amount: Int) { check(this.balance >= amount) { "余额不足" } this.balance -= amount } } Elvis 运算符 // 本质就是 val displayName = if (name != null) name else "默认值" val displayName = name ?: "默认值 takeIf - 条件取值 val validAge = age.takeIf { it > 0 } // 大于0才返回,否则null val invalidAge = age.takeUnless { it > 100 } // 小于等于100才返回 let - 空安全调用,转换结果 // 最常用:空安全调用 val user: User? = getUser() user?.let { println("用户名: ${it.name}") println("年龄: ${it.age}") } // 只有user不为null才执行 // 转换结果 val result = "hello".let { it.uppercase() + "!!!" } // result = "HELLO!!!" apply - 链式调用时有用 // 没有apply的写法 val textView = TextView(this) textView.text = "标题" textView.textSize = 18f textView.setTextColor(Color.BLACK) addView(textView) // 需要保存变量 // 用apply - 可以直接链式调用 addView(TextView(this).apply { text = "标题" textSize = 18f setTextColor(Color.BLACK) }) // 不需要临时变量 with/run - 用处不大,装逼用的 // with 的所谓"优势" with(sharedPreferences.edit()) { putString("name", "张三") putInt("age", 25) apply() } // 不用 with 直接写 val editor = sharedPreferences.edit() editor.putString("name", "张三") editor.putInt("age", 25) editor.apply() observable 简化版 fun <T> observable(initialValue: T, onChange: (KProperty<*>, T, T) -> Unit) { return object { private var value = initialValue operator fun getValue(thisRef: Any?, property: KProperty<*>): T { return value // get时直接返回 } operator fun setValue(thisRef: Any?, property: KProperty<*>, newValue: T) { val oldValue = value value = newValue // 先设置新值 onChange(property, oldValue, newValue) // 然后调用你的回调 } } } by 本质是把属性的 get/set 操作委托给另一个对象 ...

June 27, 2025 · 3 min

Create a RESTful Web Service With a Database Using Spring Boot

没有什么比官方教程更好的了 官方链接 那就做个简单的 demo 方便以后查询 创建项目,添加依赖 Web | Spring Web SQL | Spring Data JDBC SQL | H2 Database 创建数据类 @Table("TASKS") data class Task(val name: String, @Id var id: String? = null) 创建 Controller 层 @RestController @RequestMapping("/") class TaskController(private val service: TaskService) { @GetMapping fun listTasks() = ResponseEntity.ok(service.findTasks()) @GetMapping("/{id}") fun getTaskById(@PathVariable id: String) = service.findTaskById(id).toResponseEntity() @DeleteMapping("/{id}") fun delete(@PathVariable id: String) = service.deleteTaskById(id) @PostMapping fun post(@RequestBody task: Task): ResponseEntity<Task> { val savedTask = service.save(task) return ResponseEntity.created(URI("/${savedTask.id}")).body(savedTask) } private fun Task?.toResponseEntity() = this?.let { ResponseEntity.ok(it) } ?: ResponseEntity.notFound().build() } 创建数据库接口 interface TaskRepository : CrudRepository<Task, String> 实现Service层 @Service class TaskService(private val db: TaskRepository) { fun findTasks(): List<Task> = db.findAll().toList() fun findTaskById(id: String): Task? = db.findByIdOrNull(id) fun save(task: Task): Task = db.save(task) fun deleteTaskById(id: String) = db.deleteById(id) } 创建数据库初始化脚本 在 src/main/resources/schema.sql 创建: CREATE TABLE IF NOT EXISTS tasks ( id VARCHAR(60) DEFAULT RANDOM_UUID() PRIMARY KEY, name VARCHAR NOT NULL ); 配置application.properties spring.application.name=demo spring.datasource.driver-class-name=org.h2.Driver spring.datasource.url=jdbc:h2:file:./data/testdb spring.datasource.username=name spring.datasource.password=password spring.sql.init.schema-locations=classpath:schema.sql spring.sql.init.mode=always 这里的 name 是项目名称,第三行的数据库 URL 有两种选择: ...

June 23, 2025 · 2 min