Kotlin关键字
外观
Kotlin关键字[编辑 | 编辑源代码]
介绍[编辑 | 编辑源代码]
Kotlin关键字是Kotlin编程语言中具有特殊含义的保留标识符,用于定义语法结构、控制流程或声明特定行为。这些关键字不能用作变量名、函数名或其他自定义标识符。Kotlin的关键字分为两类:
- 硬关键字(Hard Keywords):始终不能作为标识符
- 软关键字(Soft Keywords):在特定上下文外可作为标识符使用
关键字分类[编辑 | 编辑源代码]
硬关键字[编辑 | 编辑源代码]
以下关键字在任何情况下都不能用作标识符:
// 声明相关
class, fun, val, var, const, typealias
// 控制流
if, else, when, for, while, do, break, continue, return
// 异常处理
try, catch, finally, throw
// 面向对象
interface, object, companion, this, super
// 类型系统
is, in, !in, as, as?
// 其他
package, import, where, by, get, set, field, dynamic, typeof
软关键字[编辑 | 编辑源代码]
这些关键字在特定上下文外可用作标识符:
// 仅在特定位置作为关键字
file, init, param, setparam, property, receiver
// 注解相关
annotation, crossinline, data, enum, inner, internal,
lateinit, noinline, open, operator, out, override,
private, protected, public, reified, sealed, suspend,
tailrec, vararg, inline, value, expect, actual
重要关键字详解[编辑 | 编辑源代码]
val 与 var[编辑 | 编辑源代码]
val声明只读变量(不可变引用),var声明可变变量:
fun main() {
val pi = 3.14 // 不可变
var counter = 0 // 可变
// pi = 3.1415 // 编译错误:Val cannot be reassigned
counter++ // 允许修改
println("PI: $pi, Counter: $counter")
}
输出:
PI: 3.14, Counter: 1
when 表达式[编辑 | 编辑源代码]
Kotlin的when取代了传统switch语句,功能更强大:
fun describe(obj: Any): String = when (obj) {
1 -> "One"
"Hello" -> "Greeting"
is Long -> "Long number"
!is String -> "Not a string"
else -> "Unknown"
}
fun main() {
println(describe(1)) // 输出: One
println(describe("Hello")) // 输出: Greeting
println(describe(1000L)) // 输出: Long number
println(describe(2.0)) // 输出: Not a string
println(describe("other")) // 输出: Unknown
}
data class[编辑 | 编辑源代码]
data关键字自动生成常用方法(toString(), equals(), hashCode(), copy()等):
data class User(val name: String, val age: Int)
fun main() {
val user1 = User("Alice", 25)
val user2 = user1.copy(age = 26)
println(user1) // 输出: User(name=Alice, age=25)
println(user1 == user2) // 输出: false
println(user1.hashCode())
}
修饰符关键字[编辑 | 编辑源代码]
可见性修饰符[编辑 | 编辑源代码]
Kotlin提供四种可见性修饰符:
示例:
open class Parent {
private val a = 1
protected open val b = 2
internal val c = 3
val d = 4 // 默认public
}
class Child : Parent() {
// a不可见
override val b = 5 // 可访问父类的protected成员
// c和d保持可见
}
高级关键字[编辑 | 编辑源代码]
reified 与内联函数[编辑 | 编辑源代码]
reified允许在运行时访问泛型类型信息:
inline fun <reified T> checkType(value: Any) {
if (value is T) {
println("Value is of type ${T::class.simpleName}")
} else {
println("Value is NOT of type ${T::class.simpleName}")
}
}
fun main() {
checkType<String>("Hello") // 输出: Value is of type String
checkType<Int>("World") // 输出: Value is NOT of type Int
}
sealed 类[编辑 | 编辑源代码]
sealed类限制继承层级,常用于表示受限的类继承结构:
sealed class Result<out T> {
data class Success<out T>(val data: T) : Result<T>()
data class Error(val exception: Exception) : Result<Nothing>()
object Loading : Result<Nothing>()
}
fun handleResult(result: Result<String>) = when(result) {
is Result.Success -> println("Data: ${result.data}")
is Result.Error -> println("Error: ${result.exception}")
Result.Loading -> println("Loading...")
// 不需要else分支,因为所有情况已覆盖
}
实际应用案例[编辑 | 编辑源代码]
使用 by 关键字实现委托[编辑 | 编辑源代码]
Kotlin通过by关键字支持委托模式:
interface Database {
fun save(data: String)
}
class RealDatabase : Database {
override fun save(data: String) {
println("Saving '$data' to real database")
}
}
class DatabaseProxy(db: Database) : Database by db {
override fun save(data: String) {
println("Logging save operation")
if (data.isNotBlank()) {
// 委托给RealDatabase
(this as Database).save(data)
}
}
}
fun main() {
val db = DatabaseProxy(RealDatabase())
db.save("Kotlin is awesome!")
}
输出:
Logging save operation Saving 'Kotlin is awesome!' to real database
数学公式示例[编辑 | 编辑源代码]
当讨论类型安全时,可以用公式表示类型转换的安全性:
其中表示安全类型转换操作。
总结[编辑 | 编辑源代码]
Kotlin的关键字系统设计既简洁又强大,通过合理使用这些关键字可以:
- 编写更安全的代码(val, null安全相关关键字)
- 创建更清晰的语法结构(when, data class)
- 实现高级编程范式(reified, sealed)
- 管理可见性和作用域(public, internal等)
理解这些关键字是掌握Kotlin语言的基础,建议通过实际编码练习来熟悉它们的用法。