kotli常用语法速记表

语法元素 描述 代码示例
变量声明 Kotlin中的变量可以是可变的(var)或者只读的(val)。 var x = 5
val y = 4
字符串模板 在字符串中插入变量或表达式的值。 val name = "Kotlin"
println("Hello, $name")
条件表达式 ifelse用于条件表达式。 val max = if (a > b) a else b
循环 forwhile用于循环。 for (item in collection) println(item)
while (x > 0) x--
范围 ..运算符用于创建范围。 for (i in 1..5) println(i)
使用class关键字定义类。 class MyClass { /*...*/ }
函数 使用fun关键字定义函数。 fun add(a: Int, b: Int): Int { return a + b }
空值安全 Kotlin有内建的null安全支持。 var a: String? = null
a?.length
类型检查和转换 isas用于类型检查和转换。 if (obj is String) { val str = obj as String }
异常处理 trycatchfinallythrow用于异常处理。 try { /*...*/ } catch (e: SomeException) { /*...*/ } finally { /*...*/ }
扩展函数 Kotlin允许你为一个已存在的类添加新的函数,这个函数就像是这个类本身的一部分一样。 fun String.lastChar(): Char = this[this.length - 1]
数据类 数据类用于存储数据,编译器会自动为数据类生成equals()hashCode()toString()和其他一些函数。 data class User(val name: String, val age: Int)
密封类 密封类用于表示受限的类继承结构,即一个值可以有一种有限的类型之一,但不能有任何其他类型。 sealed class Expr
data class Const(val number: Double) : Expr()
data class Sum(val e1: Expr, val e2: Expr) : Expr()
协程 协程是Kotlin中的一种轻量级线程,用于进行异步编程和更简洁的并发。 fun main() = runBlocking { /*...*/ }
集合操作 Kotlin提供了丰富的集合操作函数,如mapfilterreduce等。 val numbers = listOf(1, 2, 3)
numbers.map { it * 2 }
操作符重载 Kotlin允许你为自定义类型重载预定义的一组操作符。 operator fun BigInteger.plus(other: BigInteger): BigInteger
委托属性 委托属性允许将属性的getter和setter委托给另一个对象。 class Example { var p: String by Delegate() }
高阶函数和Lambda表达式 Kotlin支持高阶函数和Lambda表达式,使得你可以将函数作为参数传递,或者将函数作为结果返回。 fun List.customFilter(predicate: (T) -> Boolean): List

这个表格包含了Kotlin的许多常用语法元素,但并不全面。更多的语法元素和细节,你可以在Kotlin官方文档中找到。

你可能感兴趣的:(kotlin)