Kotlin基础学习记录

变量和函数

变量

kotlin 复制代码
// val为常量,一旦赋值就不可变
val a = 10
val a: Int = 10
a = 3 // 报错

// var为变量
var a = 10
a = 3
var b: Int = 20
b = 2

函数

kotlin 复制代码
 fun add(a: Int, b: Int): Unit {
    a += b // 报错,参数默认val
}
    
fun add(a: Int, b: Int) {
    var x: Int = a
    x += b
}
    
fun add(a: Int, b: Int): Int {
    return a + b // 或者val c = a + b  retun c
}
	
// 还可以再精简
fun add(a: Int, b: Int) = a + b
    
// 调用函数
val a: Int = 1
val b: Int = 2
add(a, b) // 返回值为Unit的函数
val c = add(a, b) // 返回值为Int的函数

逻辑控制

if条件语句

kotlin 复制代码
val a: Int = 1
val b: Int = 2
var v: Int = 0
if (a > b) {
    v = a
} else {
    v = b
}
        
// 也可以写成
var v = if (a > b) a else b // var v = if (a > b) {a} else {b}等价

var v = if (a == 1) a else if (a == 2) b else c

when条件语句

kotlin 复制代码
var a: Int = 0
when (a) {
    1 -> Log.d("tag", "1")
    2 -> Log.d("tag", "2")
    else -> Log.d("tag", "else")
}
        
when {
    a == 1 -> Log.d("tag", "1")
    a == 2 -> Log.d("tag", "2")
    else -> Log.d("tag", "else")
}

fun get(a: Int) = when(a) {
    1 -> Log.d("tag", "1")
    else -> Log.d("tag", "2")
}

循环语句

kotlin 复制代码
val range = 1..10 // 1到10闭区间
for (i in 1..10) // 从1到10遍历
for (i in 1 until 10) // 从1到9遍历
for (i in 10 downTo 1) // 从10到1遍历
for (i in 1 until 10 step 2) // 相当于for (int i = 1; i < 10; i += 2)

面向对象

类与对象

kotlin 复制代码
open class Person(val age: Int) {
    init {
        val x = age
        Log.d("tag" , "init x = $x")
    }
    constructor(): this(1) {
        Log.d("tag", "constructor")
    }
    fun print() {
        Log.d("tag", "Person")
    }
}

class Student(val id: Int, age: Int) : Person(age) {
    init {
        Log.d("tag", "init student")
    }
}

接口

kotlin 复制代码
interface Study {
    fun read() { // 默认实现
        Log.d("tag", "default read")
    }
    fun say() {
        Log.d("tag", "default say")
    }
}

open class Person(val age: Int) {
    init {
        val x = age
        Log.d("tag" , "init x = $x")
    }
    constructor(): this(1) {
        Log.d("tag", "constructor")
    }
    fun print() {
        Log.d("tag", "Person")
    }
}

class Student(val id: Int, age: Int) : Person(age), Study { // 继承接口
    init {
        Log.d("tag", "init student")
    }

    override fun read() { // 重写
        Log.d("tag", "student read")
    }
}

fun doStudy(study: Study) { // 调用接口函数
    study.read()
    study.say()
}

// 调用方法
val student = Student(1, 2)
doStudy(student)

数据类和单例类

kotlin 复制代码
data class data(val a: String, val b: String) // 数据类

// object单例类,实现为饿汉单例
object get {
    fun print() {
        Log.d("tag", "this is a class")
    }
}

// 单例类使用
get.print() // 不需要创建对象

// 伴生对象实现懒汉单例
// 第一种实现:顶层val + by lazy
val instance by lazy {
    Instance()
}
    
class Instance {
    fun print() {
        Log.d("tag", "Instance")
    }
}

// 第二种实现:伴生对象实现
class Test private constructor() {
    companion object {
        val instance: Test by lazy {
            Test()
        }
    }
    fun print() {
        Log.d("tag", "instance")
    }
}

List(MutableList), ArrayList, Map(MutableMap), Set(MutableSet)

List & MutableList

kotlin 复制代码
// 创建
val a: List<Int> = listOf(1, 2, 3) // 不加List<Int>也可以自己推断
val b: MutableList<Int> = MutableListOf(1, 2, 3) // 同上

// 查询
val x = a[0] // 1
val x = a.indexOf(1) // 0
val x = a.slice(0..1) // [1, 2]

// 添加
b.add(1) // 末尾加
b.add(0, 1) // 指定索引加

// 删除
b.remove(2) // 按值删
b.removeAt(1) // 按索引删

// 排序
val sorted = roList.sorted()              // 升序
val desc = roList.sortedDescending()
val custom = roList.sortedBy { -it }

// 转换
val x: List<Int> = b.toList()

// 去重
val list = listOf(1,2,2,3)
val unique = list.distinct()    // [1,2,3]
```
ArrayList(基本和数组还有List一样,为List底层)
Set & MutableSet
```kotlin
// 创建
val a: Set<Int> = setOf(1, 2, 3)
val b: MutableSet<Int> = mutableSetOf(1, 2, 3)
val c = linkedSetOf(1, 4, 2) // 有序

// 操作
b.add(5)
b.remove(5)

// 集合运算
val a = setOf(1,2,3)
val b = setOf(3,4,5)
val union = a union b           // [1,2,3,4,5]
val inter = a intersect b       // [3]
val diff  = a subtract b        // [1,2]
```
Map & MutableMap
```kotlin
// 创建
val roMap: Map<String, Int> = mapOf("a" to 1, "b" to 2)
val mutMap: MutableMap<String, Int> = mutableMapOf()
val linkedMap = linkedMapOf("c" to 3, "a" to 1) // 有序

// 遍历
roMap.forEach { (k, v) -> println("$k=$v") }
for ((k, v) in roMap) { ... }

// 转换
val swapped = roMap.map { (k, v) -> v to k }.toMap() // 值变键
```
相关推荐
Kapaseker10 小时前
一杯美式搞定 Kotlin 空安全
android·kotlin
FunnySaltyFish1 天前
什么?Compose 把 GapBuffer 换成了 LinkBuffer?
算法·kotlin·android jetpack
Kapaseker1 天前
Compose 进阶—巧用 GraphicsLayer
android·kotlin
Kapaseker2 天前
实战 Compose 中的 IntrinsicSize
android·kotlin
A0微声z4 天前
Kotlin Multiplatform (KMP) 中使用 Protobuf
kotlin
alexhilton5 天前
使用FunctionGemma进行设备端函数调用
android·kotlin·android jetpack
lhDream5 天前
Kotlin 开发者必看!JetBrains 开源 LLM 框架 Koog 快速上手指南(含示例)
kotlin
RdoZam5 天前
Android-封装基类Activity\Fragment,从0到1记录
android·kotlin
Kapaseker5 天前
研究表明,开发者对Kotlin集合的了解不到 20%
android·kotlin
郑州光合科技余经理6 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php