阅读视图
kotlin-5
太棒了!现在让我们进入 Kotlin 更深入的高级特性和实际应用场景。这部分将涵盖泛型、注解、反射、DSL等企业级开发必备技能。
Kotlin 高级特性:企业级开发实战
三十二、泛型深入:型变、星投影与 reified
1. 型变(Variance)
// 不变(Invariant)- 默认行为
class Box<T>(val value: T)
fun main() {
val stringBox = Box("Hello")
// val anyBox: Box<Any> = stringBox // 错误!Box<String> 不是 Box<Any> 的子类型
}
// 协变(Covariant)- 使用 out 关键字
class ReadOnlyBox<out T>(val value: T) {
fun get(): T = value
// fun set(newValue: T) {} // 错误!不能有消费 T 的方法
}
// 逆变(Contravariant)- 使用 in 关键字
class WriteOnlyBox<in T> {
fun set(value: T) {
println("设置值: $value")
}
// fun get(): T // 错误!不能有生产 T 的方法
}
fun testVariance() {
// 协变示例
val stringBox: ReadOnlyBox<String> = ReadOnlyBox("Text")
val anyBox: ReadOnlyBox<Any> = stringBox // 正确!因为 out 关键字
// 逆变示例
val anyWriteBox: WriteOnlyBox<Any> = WriteOnlyBox()
val stringWriteBox: WriteOnlyBox<String> = anyWriteBox // 正确!因为 in 关键字
}
2. 星投影(Star Projection)
fun printSize(list: List<*>) {
println("列表大小: ${list.size}")
// println(list[0]) // 不能安全地访问元素内容
}
fun <T> compareFirstSecond(list: List<T>, comparator: Comparator<in T>): Boolean
where T : Comparable<T> {
return if (list.size >= 2) {
comparator.compare(list[0], list[1]) > 0
} else false
}
// 使用 reified 关键字实现类型检查
inline fun <reified T> checkType(value: Any): Boolean {
return value is T
}
fun main() {
val list = listOf(1, 2, 3)
printSize(list)
println(checkType<String>("Hello")) // true
println(checkType<Int>("Hello")) // false
}
三十三、注解与反射
1. 自定义注解
// 定义注解
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
annotation class ApiVersion(val version: String)
@Target(AnnotationTarget.PROPERTY)
annotation class JsonExclude
@Target(AnnotationTarget.PROPERTY)
annotation class JsonName(val name: String)
// 使用注解
@ApiVersion("1.0")
data class User(
@JsonName("user_name")
val name: String,
val age: Int,
@JsonExclude
val password: String
)
// 注解处理器模拟
fun processAnnotations(obj: Any) {
val klass = obj::class
val apiVersion = klass.annotations.find { it is ApiVersion } as? ApiVersion
apiVersion?.let { println("API 版本: ${it.version}") }
klass.memberProperties.forEach { prop ->
prop.annotations.forEach { annotation ->
when (annotation) {
is JsonName -> println("属性 ${prop.name} 将被序列化为 ${annotation.name}")
is JsonExclude -> println("属性 ${prop.name} 将被排除")
}
}
}
}
2. 反射实战
import kotlin.reflect.full.*
import kotlin.reflect.jvm.isAccessible
class SecretClass {
private val secretValue = "机密信息"
private fun secretMethod() = "机密方法"
public fun publicMethod() = "公开方法"
}
fun reflectExample() {
val instance = SecretClass()
val klass = instance::class
println("=== 类信息 ===")
println("类名: ${klass.simpleName}")
println("成员属性: ${klass.memberProperties.map { it.name }}")
println("成员函数: ${klass.memberFunctions.map { it.name }}")
println("\n=== 访问私有成员 ===")
// 访问私有属性
val secretProperty = klass.memberProperties.find { it.name == "secretValue" }
secretProperty?.let {
it.isAccessible = true
println("私有属性值: ${it.get(instance)}")
}
// 调用私有方法
val secretMethod = klass.memberFunctions.find { it.name == "secretMethod" }
secretMethod?.let {
it.isAccessible = true
println("私有方法结果: ${it.call(instance)}")
}
}
三十四、类型安全的构建器(DSL)
1. HTML DSL 构建器
class HtmlElement(val name: String, val content: String = "") {
private val children = mutableListOf<HtmlElement>()
private val attributes = mutableMapOf<String, String>()
fun attribute(name: String, value: String) {
attributes[name] = value
}
fun child(element: HtmlElement) {
children.add(element)
}
override fun toString(): String {
val attrString = if (attributes.isNotEmpty()) {
" " + attributes.entries.joinToString(" ") { "${it.key}="${it.value}"" }
} else ""
return if (children.isEmpty()) {
"<$name$attrString>$content</$name>"
} else {
"<$name$attrString>${children.joinToString("")}$content</$name>"
}
}
}
// DSL 构建函数
fun html(block: HtmlBuilder.() -> Unit): HtmlElement {
val builder = HtmlBuilder("html")
builder.block()
return builder.build()
}
class HtmlBuilder(private val rootName: String) {
private val root = HtmlElement(rootName)
private var currentElement: HtmlElement = root
fun head(block: HeadBuilder.() -> Unit) {
val headBuilder = HeadBuilder()
headBuilder.block()
root.child(headBuilder.build())
}
fun body(block: BodyBuilder.() -> Unit) {
val bodyBuilder = BodyBuilder()
bodyBuilder.block()
root.child(bodyBuilder.build())
}
fun build(): HtmlElement = root
}
class HeadBuilder {
private val head = HtmlElement("head")
fun title(text: String) {
head.child(HtmlElement("title", text))
}
fun build(): HtmlElement = head
}
class BodyBuilder {
private val body = HtmlElement("body")
fun h1(text: String, block: H1Builder.() -> Unit = {}) {
val h1Builder = H1Builder(text)
h1Builder.block()
body.child(h1Builder.build())
}
fun p(text: String) {
body.child(HtmlElement("p", text))
}
fun build(): HtmlElement = body
}
class H1Builder(private val text: String) {
private val h1 = HtmlElement("h1", text)
fun style(css: String) {
h1.attribute("style", css)
}
fun build(): HtmlElement = h1
}
// 使用 DSL
fun createHtmlPage() {
val page = html {
head {
title("我的网页")
}
body {
h1("欢迎来到 Kotlin DSL") {
style("color: blue;")
}
p("这是一个使用 DSL 构建的 HTML 页面")
}
}
println(page)
}
2. 数据库查询 DSL
// 查询 DSL 定义
class QueryBuilder {
private var table: String = ""
private val conditions = mutableListOf<String>()
private var limit: Int? = null
private var orderBy: String? = null
fun from(table: String) {
this.table = table
}
fun where(condition: String) {
conditions.add(condition)
}
fun limit(count: Int) {
this.limit = count
}
fun orderBy(column: String) {
this.orderBy = column
}
fun build(): String {
val query = StringBuilder("SELECT * FROM $table")
if (conditions.isNotEmpty()) {
query.append(" WHERE ").append(conditions.joinToString(" AND "))
}
orderBy?.let {
query.append(" ORDER BY $it")
}
limit?.let {
query.append(" LIMIT $it")
}
return query.toString()
}
}
// DSL 入口函数
fun query(block: QueryBuilder.() -> Unit): String {
val builder = QueryBuilder()
builder.block()
return builder.build()
}
// 使用 DSL 构建查询
fun buildQueries() {
val simpleQuery = query {
from("users")
}
println("简单查询: $simpleQuery")
val complexQuery = query {
from("orders")
where("status = 'completed'")
where("amount > 100")
orderBy("created_at DESC")
limit(10)
}
println("复杂查询: $complexQuery")
}
三十五、合约(Contracts)与内联优化
import kotlin.contracts.*
// 使用合约优化智能转换
@OptIn(ExperimentalContracts::class)
fun String?.isNotNullOrEmpty(): Boolean {
contract {
returns(true) implies (this@isNotNullOrEmpty != null)
}
return this != null && this.isNotEmpty()
}
fun processText(text: String?) {
if (text.isNotNullOrEmpty()) {
// 由于合约,编译器知道 text 不为 null
println(text.length) // 不需要安全调用
println(text.uppercase())
}
}
// 内联类 - 包装类型而不产生运行时开销
@JvmInline
value class Password(private val value: String) {
init {
require(value.length >= 8) { "密码必须至少8个字符" }
}
fun mask(): String = "*".repeat(value.length)
}
@JvmInline
value class UserId(val value: Int)
fun login(userId: UserId, password: Password) {
println("用户 ${userId.value} 登录,密码: ${password.mask()}")
}
三十六、多平台项目(KMP)基础
// 公共模块 - 共享业务逻辑
expect class Platform() {
val platform: String
}
class Greeting {
private val platform = Platform()
fun greet(): String {
return "Hello from ${platform.platform}"
}
}
// Android 实现
// androidMain/Platform.kt
actual class Platform actual constructor() {
actual val platform: String = "Android"
}
// iOS 实现
// iosMain/Platform.kt
actual class Platform actual constructor() {
actual val platform: String = "iOS"
}
// 共享业务逻辑
class Calculator {
fun add(a: Int, b: Int): Int = a + b
fun multiply(a: Int, b: Int): Int = a * b
fun calculateExpression(expression: String): Int {
return when {
expression.contains("+") -> {
val parts = expression.split("+")
add(parts[0].trim().toInt(), parts[1].trim().toInt())
}
expression.contains("*") -> {
val parts = expression.split("*")
multiply(parts[0].trim().toInt(), parts[1].trim().toInt())
}
else -> throw IllegalArgumentException("不支持的表达式")
}
}
}
三十七、性能优化与最佳实践
1. 集合操作优化
fun collectionOptimization() {
val numbers = (1..1000000).toList()
// 不好的写法:多次中间操作
val badResult = numbers
.filter { it % 2 == 0 }
.map { it * 2 }
.filter { it > 1000 }
.take(10)
// 好的写法:使用序列(惰性求值)
val goodResult = numbers.asSequence()
.filter { it % 2 == 0 }
.map { it * 2 }
.filter { it > 1000 }
.take(10)
.toList()
println("结果: $goodResult")
}
// 使用 groupBy 优化复杂操作
data class Person(val name: String, val age: Int, val city: String)
fun optimizeGrouping() {
val people = listOf(
Person("Alice", 25, "Beijing"),
Person("Bob", 30, "Shanghai"),
Person("Charlie", 25, "Beijing"),
Person("Diana", 30, "Shanghai")
)
// 按城市分组,然后按年龄分组
val grouped = people.groupBy({ it.city }, { it.age })
println("分组结果: $grouped")
// 统计每个城市的平均年龄
val averageAges = people.groupingBy { it.city }
.fold(0.0) { accumulator, element ->
accumulator + element.age
}.mapValues { it.value / people.count { p -> p.city == it.key } }
println("平均年龄: $averageAges")
}
2. 内存优化模式
// 使用对象池避免重复创建
class ConnectionPool private constructor() {
private val available = mutableListOf<Connection>()
private val inUse = mutableSetOf<Connection>()
fun getConnection(): Connection {
return available.removeFirstOrNull()?.also { inUse.add(it) }
?: Connection().also { inUse.add(it) }
}
fun releaseConnection(connection: Connection) {
inUse.remove(connection)
available.add(connection)
}
companion object {
val instance by lazy { ConnectionPool() }
}
}
class Connection {
fun connect() = println("连接建立")
fun disconnect() = println("连接关闭")
}
// 使用 use 函数自动管理资源
fun readFileSafely() {
// 模拟资源管理
val resource = object : AutoCloseable {
override fun close() = println("资源已释放")
fun read() = "文件内容"
}
val content = resource.use {
it.read()
}
println("内容: $content") // 资源会自动关闭
}
三十八、完整实战项目:构建事件总线系统
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.flow.*
import kotlin.reflect.KClass
// 事件基类
sealed class Event {
data class UserLoggedIn(val userId: String) : Event()
data class OrderCreated(val orderId: String, val amount: Double) : Event()
data class PaymentProcessed(val paymentId: String, val success: Boolean) : Event()
object SystemShutdown : Event()
}
// 事件处理器接口
interface EventHandler<T : Event> {
suspend fun handle(event: T)
}
// 事件总线
object EventBus {
private val handlers = mutableMapOf<KClass<out Event>, MutableList<EventHandler<*>>>()
private val eventChannel = Channel<Event>(Channel.UNLIMITED)
// 注册事件处理器
fun <T : Event> registerHandler(eventClass: KClass<T>, handler: EventHandler<T>) {
handlers.getOrPut(eventClass) { mutableListOf() }.add(handler as EventHandler<*>)
}
// 发布事件
fun publish(event: Event) {
eventChannel.trySend(event)
}
// 启动事件处理循环
fun start() = GlobalScope.launch {
for (event in eventChannel) {
processEvent(event)
}
}
private suspend fun processEvent(event: Event) {
val eventClass = event::class
val eventHandlers = handlers[eventClass] ?: return
eventHandlers.forEach { handler ->
try {
@Suppress("UNCHECKED_CAST")
(handler as EventHandler<Event>).handle(event)
} catch (e: Exception) {
println("事件处理失败: ${e.message}")
}
}
}
}
// 具体的事件处理器
class UserActivityLogger : EventHandler<Event.UserLoggedIn> {
override suspend fun handle(event: Event.UserLoggedIn) {
delay(100) // 模拟处理时间
println("📝 用户登录日志: ${event.userId} 在 ${System.currentTimeMillis()} 登录")
}
}
class OrderProcessor : EventHandler<Event.OrderCreated> {
override suspend fun handle(event: Event.OrderCreated) {
delay(200)
println("💰 订单处理: 订单 ${event.orderId} 金额 ${event.amount}")
}
}
class PaymentNotifier : EventHandler<Event.PaymentProcessed> {
override suspend fun handle(event: Event.PaymentProcessed) {
delay(150)
val status = if (event.success) "成功" else "失败"
println("📧 支付通知: 支付 ${event.paymentId} $status")
}
}
class SystemMonitor : EventHandler<Event.SystemShutdown> {
override suspend fun handle(event: Event.SystemShutdown) {
println("🛑 系统关闭: 开始清理资源...")
delay(500)
println("🛑 系统关闭: 资源清理完成")
}
}
// 使用事件总线
fun main() = runBlocking {
// 注册处理器
EventBus.registerHandler(Event.UserLoggedIn::class, UserActivityLogger())
EventBus.registerHandler(Event.OrderCreated::class, OrderProcessor())
EventBus.registerHandler(Event.PaymentProcessed::class, PaymentNotifier())
EventBus.registerHandler(Event.SystemShutdown::class, SystemMonitor())
// 启动事件总线
EventBus.start()
// 模拟发布事件
EventBus.publish(Event.UserLoggedIn("user123"))
EventBus.publish(Event.OrderCreated("order456", 99.99))
EventBus.publish(Event.PaymentProcessed("pay789", true))
EventBus.publish(Event.OrderCreated("order999", 49.99))
EventBus.publish(Event.PaymentProcessed("pay000", false))
delay(1000) // 等待事件处理完成
EventBus.publish(Event.SystemShutdown())
delay(1000)
println("程序结束")
}
下一步学习方向
你现在已经掌握了 Kotlin 的企业级开发技能!接下来可以深入:
- Kotlin 编译器插件开发:自定义编译期处理
- Kotlin 元编程:在编译时生成代码
- Kotlin 与 Java 互操作高级技巧:类型映射、异常处理
- Kotlin 服务端开发:使用 Ktor、Spring Boot
- Kotlin 前端开发:使用 Compose for Web
- Kotlin 移动端开发:Compose Multiplatform
这些高级特性将让你在 Kotlin 开发中游刃有余,能够构建复杂、高性能的企业级应用!