Elysia Tools

在一个清晰的工作台里浏览工具、案例、可视化和主题指南。

热门分类

专题

语言
ZHESPTRUFRDEEN

Elysia Tools

导航

编程语言

Kotlin 示例

基础Kotlin代码示例,包括Android开发、JVM后端和现代Kotlin特性

案例

这个案例集合中的条目

代码kotlin简单

Kotlin Hello World

基础Kotlin Hello World程序和现代Kotlin语法及类型安全

难度

2/10

预计时间

10 min

标签

kotlin, jvm, null safety

前置条件

Basic programming concepts

kotlin
// Kotlin Hello World Examples

// 1. Basic Hello World
fun mainBasic() {
    println("Hello, World!")
}

// 2. Hello World with variable
fun mainWithVariable() {
    val message = "Hello, World!"
    println(message)
}

// 3. Hello World with function
fun sayHello(): String {
    return "Hello, World!"
}

fun mainWithFunction() {
    println(sayHello())
}

// 4. Hello World with parameters
fun greet(name: String): String {
    return "Hello, $name!"
}

fun mainWithParameters() {
    println(greet("World"))
    println(greet("Kotlin"))
}

// 5. Hello World with class
class Greeter(private val message: String = "Hello, World!") {
    fun greet() {
        println(message)
    }
}

fun mainWithClass() {
    val greeter = Greeter()
    greeter.greet()
}

// 6. Hello World with user input
fun mainWithInput() {
    print("Enter your name: ")
    val name = readLine()
    println("Hello, ${name ?: "World"}!")
}

// 7. Hello World multiple times
fun mainMultipleTimes() {
    for (i in 1..5) {
        println("Hello, World! $i")
    }
}

// 8. Hello World with collection
fun mainWithCollection() {
    val greetings = listOf("Hello", "Bonjour", "Hola", "Ciao", "こんにちは")
    greetings.forEach { greeting ->
        println("$greeting, World!")
    }
}

// 9. Hello World with map
fun mainWithMap() {
    val greetings = mapOf(
        "en" to "Hello",
        "es" to "Hola",
        "fr" to "Bonjour",
        "de" to "Hallo",
        "ja" to "こんにちは"
    )

    greetings.forEach { (lang, greeting) ->
        println("$greeting, World! ($lang)")
    }
}

// 10. Hello World with data class
data class HelloResponse(
    val message: String,
    val timestamp: Long = System.currentTimeMillis(),
    val success: Boolean = true
)

fun mainWithDataClass() {
    val response = HelloResponse("Hello, World!")
    println(response)
}

// Basic data types examples
fun mainDataTypes() {
    // Kotlin is statically typed with type inference
    val integer: Int = 42
    val double: Double = 3.14
    val float: Float = 3.14f
    val long: Long = 42L
    val string: String = "Hello, Kotlin!"
    val boolean: Boolean = true
    val char: Char = 'K'
    val array: Array<Int> = arrayOf(1, 2, 3, 4, 5)
    val list: List<Int> = listOf(1, 2, 3, 4, 5)
    val map: Map<String, Any> = mapOf(
        "name" to "John Doe",
        "age" to 30,
        "email" to "[email protected]"
    )
    val nullable: String? = null

    println("Integer: $integer, Type: ${integer::class.simpleName}")
    println("Double: $double, Type: ${double::class.simpleName}")
    println("Float: $float, Type: ${float::class.simpleName}")
    println("Long: $long, Type: ${long::class.simpleName}")
    println("String: $string, Type: ${string::class.simpleName}")
    println("Boolean: $boolean, Type: ${boolean::class.simpleName}")
    println("Char: $char, Type: ${char::class.simpleName}")
    println("Array: ${array.contentToString()}, Type: ${array::class.simpleName}")
    println("List: $list, Type: ${list::class.simpleName}")
    println("Map: $map, Type: ${map::class.simpleName}")
    println("Nullable: ${nullable ?: "null"}, Type: ${nullable?.let { it::class.simpleName } ?: "Null"}")

    // Control flow examples
    val age = 18
    if (age >= 18) {
        println("You are an adult")
    } else {
        println("You are a minor")
    }

    // When expression (Kotlin's switch)
    val grade = 'A'
    when (grade) {
        'A' -> println("Excellent!")
        'B' -> println("Good job!")
        'C' -> println("Fair enough")
        else -> println("Need improvement")
    }

    // Loop examples
    val fruits = listOf("apple", "banana", "cherry")
    for (index, fruit) in fruits.withIndex() {
        println("${index + 1}. I like $fruit")
    }

    // Range operations
    for (i in 1..10) {
        println("Number: $i")
    }

    // Collection operations examples
    val numbers = (1..10).toList()
    val evenNumbers = numbers.filter { it % 2 == 0 }
    val squaredNumbers = numbers.map { it * it }
    val sum = numbers.reduce { acc, num -> acc + num }

    println("Even numbers: $evenNumbers")
    println("Squared numbers: $squaredNumbers")
    println("Sum: $sum")

    // String methods examples
    val text = "Hello, Kotlin Programming!"
    println("Uppercase: ${text.uppercase()}")
    println("Lowercase: ${text.lowercase()}")
    println("Capitalized: ${text.replaceFirstChar { it.uppercase() }}")
    println("Length: ${text.length}")
    println("Reversed: ${text.reversed()}")

    // Null safety examples
    val nullableString: String? = "NotNull"
    val length = nullableString?.length ?: 0
    println("Length: $length")

    val definitelyNotNull: String = nullableString!!
    println("Not null: $definitelyNotNull")

    // Elvis operator
    val result = nullableString ?: "Default value"
    println("Result: $result")

    // Safe call with let
    nullableString?.let {
        println("Value exists: $it")
    }

    // Method chaining with scope functions
    val processedText = text
        .split(" ")
        .filter { it.isNotBlank() }
        .map { it.lowercase() }
        .joinToString("-")

    println("Processed text: $processedText")
}
代码kotlin中等

Kotlin 面向对象编程

高级OOP概念,包括类、继承、接口和Kotlin特有特性

难度

7/10

预计时间

35 min

标签

kotlin, oop, advanced

前置条件

Basic Kotlin syntax, Object-oriented concepts

kotlin
// Kotlin Object-Oriented Programming Examples

// 1. Classes and Properties
class Person(
    val name: String,           // Read-only property
    var age: Int,              // Mutable property
    private var _email: String = ""  // Private property with backing field
) {
    // Custom getter
    var email: String
        get() = _email
        set(value) {
            if (value.contains("@")) {
                _email = value
            }
        }

    // Custom getter with derived property
    val isAdult: Boolean
        get() = age >= 18

    // Secondary constructor
    constructor(name: String) : this(name, 0)

    // Member function
    fun introduce(): String {
        return "Hi, I'm \$name and I'm \$age years old."
    }

    // Init block
    init {
        println("Person \$name created")
    }
}

// 2. Data Classes
data class User(
    val id: Long,
    val username: String,
    val email: String,
    val isActive: Boolean = true
) {
    // Custom component in data class
    val displayName: String
        get() = username.replaceFirstChar { it.uppercase() }
}

fun demonstrateDataClass() {
    val user1 = User(1, "john_doe", "[email protected]")
    val user2 = user1.copy(username = "jane_doe", id = 2)

    println("User 1: $user1")
    println("User 2: $user2")
    println("Display names: ${user1.displayName}, ${user2.displayName}")
}

// 3. Sealed Classes and Enums
sealed class Result<out T> {
    data class Success<out T>(val data: T) : Result<T>()
    data class Error(val exception: Throwable) : Result<Nothing>()
    object Loading : Result<Nothing>()
}

enum class Status {
    ACTIVE, INACTIVE, PENDING, COMPLETED;

    fun isFinal(): Boolean {
        return this == COMPLETED
    }

    companion object {
        fun fromString(value: String): Status? {
            return values().find { it.name.equals(value, ignoreCase = true) }
        }
    }

    val displayName: String
        get() = name.lowercase().replaceFirstChar { it.uppercase() }
}

// 4. Interfaces
interface Drawable {
    fun draw()
    val area: Double
}

interface Movable {
    fun move(dx: Double, dy: Double)
}

// Multiple interface implementation
class Circle(
    private var radius: Double,
    private var x: Double = 0.0,
    private var y: Double = 0.0
) : Drawable, Movable {

    init {
        require(radius > 0) { "Radius must be positive" }
    }

    override val area: Double
        get() = Math.PI * radius * radius

    override fun draw() {
        println("Drawing circle at ($x, $y) with radius $radius")
    }

    override fun move(dx: Double, dy: Double) {
        x += dx
        y += dy
        println("Circle moved to ($x, $y)")
    }

    // Property with custom setter
    var diameter: Double
        get() = radius * 2
        set(value) {
            radius = value / 2
        }
}

// 5. Inheritance
abstract class Animal(
    protected val name: String,
    protected val age: Int
) {
    abstract fun makeSound()

    fun eat(): String {
        return "\$name is eating"
    }
}

class Dog(
    name: String,
    age: Int,
    val breed: String
) : Animal(name, age) {

    override fun makeSound() {
        println("\$name barks: Woof!")
    }

    fun wagTail() {
        println("\$name is wagging its tail")
    }

    // Property with custom getter
    val isPuppy: Boolean
        get() = age < 1
}

class Cat(
    name: String,
    age: Int,
    var color: String
) : Animal(name, age) {

    override fun makeSound() {
        println("\$name meows: Meow!")
    }

    fun purr() {
        println("\$name is purring")
    }

    override fun eat(): String {
        return super.eat() + " cat food"
    }
}

// 6. Abstract Class with Factory Pattern
abstract class Vehicle {
    abstract val brand: String
    abstract val model: String
    abstract val year: Int

    abstract fun start()
    abstract fun stop()

    fun info(): String {
        return "\$year \$brand \$model"
    }

    companion object {
        fun createCar(brand: String, model: String, year: Int): Car {
            return Car(brand, model, year)
        }

        fun createMotorcycle(brand: String, model: String, year: Int): Motorcycle {
            return Motorcycle(brand, model, year)
        }
    }
}

class Car(
    override val brand: String,
    override val model: String,
    override val year: Int,
    val numberOfDoors: Int = 4
) : Vehicle() {

    override fun start() {
        println("\$brand \$model engine started")
    }

    override fun stop() {
        println("\$brand \$model engine stopped")
    }

    fun openTrunk() {
        println("Trunk opened")
    }
}

class Motorcycle(
    override val brand: String,
    override val model: String,
    override val year: Int,
    val hasStorage: Boolean = false
) : Vehicle() {

    override fun start() {
        println("\$brand \$model engine started")
    }

    override fun stop() {
        println("\$brand \$model engine stopped")
    }

    fun wheelie() {
        println("Doing a wheelie!")
    }
}

// 7. Object (Singleton)
object Database {
    private val connections = mutableListOf<String>()

    fun addConnection(connectionString: String) {
        connections.add(connectionString)
        println("Added connection: $connectionString")
    }

    fun getConnectionCount(): Int {
        return connections.size
    }

    fun clearConnections() {
        connections.clear()
        println("All connections cleared")
    }
}

// 8. Companion Object (Factory methods)
class HttpClient private constructor(
    private val baseUrl: String,
    private val timeout: Int
) {
    fun get(endpoint: String): String {
        return "GET $baseUrl$endpoint"
    }

    companion object {
        fun createDefault(): HttpClient {
            return HttpClient("https://api.example.com", 30)
        }

        fun createCustom(baseUrl: String, timeout: Int): HttpClient {
            return HttpClient(baseUrl, timeout)
        }
    }
}

// 9. Extension Functions
fun String.isEmail(): Boolean {
    return this.contains("@") && this.contains(".")
}

fun String.capitalizeWords(): String {
    return this.split(" ")
        .joinToString(" ") { it.replaceFirstChar { it.uppercase() } }
}

fun Int.isEven(): Boolean = this % 2 == 0

fun List<Int>.sumOfSquares(): Int = this.map { it * it }.sum()

// Extension properties
val String.isValidPassword: Boolean
    get() = this.length >= 8 && this.any { it.isUpperCase() } && this.any { it.isDigit() }

// 10. Generic Classes
class Stack<T>(private vararg val items: T) {
    private val elements = mutableListOf(*items)

    fun push(item: T) {
        elements.add(item)
    }

    fun pop(): T? {
        return if (elements.isNotEmpty()) {
            elements.removeAt(elements.size - 1)
        } else {
            null
        }
    }

    fun peek(): T? {
        return elements.lastOrNull()
    }

    val size: Int
        get() = elements.size

    val isEmpty: Boolean
        get() = elements.isEmpty()

    fun <R> map(transform: (T) -> R): Stack<R> {
        return Stack<R>(*elements.map(transform).toTypedArray())
    }
}

// 11. Delegation
interface Logger {
    fun log(message: String)
    fun error(message: String)
}

class ConsoleLogger : Logger {
    override fun log(message: String) {
        println("LOG: $message")
    }

    override fun error(message: String) {
        println("ERROR: $message")
    }
}

class FileLogger : Logger {
    private val filename = "app.log"

    override fun log(message: String) {
        // Write to file
        println("FILE LOG: $message")
    }

    override fun error(message: String) {
        // Write error to file
        println("FILE ERROR: $message")
    }
}

// Delegated logger
class UserService(
    private val logger: Logger
) : Logger by logger {

    fun createUser(name: String, email: String): User {
        log("Creating user: $name")

        // Simulate user creation
        val user = User(
            id = System.currentTimeMillis(),
            username = name.lowercase().replace(" ", "_"),
            email = email
        )

        log("User created with ID: ${user.id}")
        return user
    }

    fun deleteUser(userId: Long) {
        error("User deletion requested for ID: $userId")
        // Delete user logic here
    }
}

// 12. Scope Functions
fun demonstrateScopeFunctions() {
    // apply: used for object configuration
    val person = Person("Alice", 25).apply {
        age = 26
        email = "[email protected]"
    }

    // let: executes block on non-null object and returns result
    val result = person.let {
        "User: ${it.name}, Age: ${it.age}"
    }

    // run: similar to let but for object and returns any type
    val userStatus = person.run {
        when {
            isAdult -> "Adult"
            age < 13 -> "Child"
            else -> "Teenager"
        }
    }

    // also: similar to apply but returns object (for chaining)
    val configuredPerson = person.also {
        println("Configured person: \${it.name}")
    }

    println("Result: \$result")
    println("Status: \$userStatus")
    println("Final person: \${configuredPerson.name}")
}

// Main function demonstrating all concepts
fun main() {
    // Data class demo
    demonstrateDataClass()

    // Sealed class demo
    val result1: Result<String> = Result.Success("Data loaded successfully")
    val result2: Result<String> = Result.Error(Exception("Network error"))

    when (result1) {
        is Result.Success -> println("Success: ${result1.data}")
        is Result.Error -> println("Error: ${result2.exception.message}")
        is Result.Loading -> println("Loading...")
    }

    // Inheritance demo
    val dog = Dog("Buddy", 3, "Golden Retriever")
    val cat = Cat("Whiskers", 2, "gray")

    dog.makeSound()
    dog.wagTail()
    cat.makeSound()
    cat.purr()

    // Vehicle factory demo
    val car = Vehicle.createCar("Toyota", "Camry", 2022)
    val motorcycle = Vehicle.createMotorcycle("Harley", "Davidson", 2021)

    car.start()
    car.openTrunk()
    motorcycle.start()
    motorcycle.wheelie()

    // Singleton demo
    Database.addConnection("localhost:5432")
    Database.addConnection("remote:5432")
    println("Total connections: ${Database.getConnectionCount()}")

    // Extension functions demo
    val email = "[email protected]"
    val words = "hello world kotlin programming"
    val numbers = listOf(1, 2, 3, 4, 5)

    println("Is email: ${email.isEmail()}")
    println("Capitalized: ${words.capitalizeWords()}")
    println("Even numbers count: ${numbers.count { it.isEven() }}")
    println("Sum of squares: ${numbers.sumOfSquares()}")
    println("Password valid: ${"Password123".isValidPassword}")

    // Generic stack demo
    val intStack = Stack(1, 2, 3)
    intStack.push(4)
    println("Popped: ${intStack.pop()}")
    println("Stack size: ${intStack.size}")

    // Delegation demo
    val consoleLogger = ConsoleLogger()
    val userService = UserService(consoleLogger)
    val user = userService.createUser("John Doe", "[email protected]")
    userService.deleteUser(user.id)

    // Scope functions demo
    demonstrateScopeFunctions()
}
代码kotlin复杂

Kotlin 协程与并发

现代Kotlin协程用于异步编程、结构化并发和并行处理

难度

9/10

预计时间

50 min

标签

kotlin, coroutines, async, parallel

前置条件

Advanced Kotlin, Concurrency concepts, Kotlin coroutines library

kotlin
// Kotlin Coroutines and Concurrency Examples

import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.sync.*
import kotlin.random.Random
import kotlin.system.measureTimeMillis

// 1. Basic Coroutine Launch
fun basicCoroutineExample() = runBlocking {
    println("Start")

    // Launch a new coroutine
    launch {
        delay(1000) // Non-blocking delay
        println("Inside launch")
    }

    println("End of runBlocking")
}

// 2. Async/Await Pattern
suspend fun fetchUserData(): User {
    delay(1000) // Simulate network call
    return User(
        id = Random.nextLong(),
        username = "user_${Random.nextInt()}",
        email = "user${Random.nextInt()}@example.com"
    )
}

fun asyncAwaitExample() = runBlocking {
    val time = measureTimeMillis {
        // Launch multiple async operations
        val deferred1 = async { fetchUserData() }
        val deferred2 = async { fetchUserData() }
        val deferred3 = async { fetchUserData() }

        // Wait for all results
        val user1 = deferred1.await()
        val user2 = deferred2.await()
        val user3 = deferred3.await()

        println("Users fetched: ${user1.username}, ${user2.username}, ${user3.username}")
    }

    println("Total time: $time ms")
}

// 3. Coroutine Contexts and Dispatchers
fun dispatchersExample() = runBlocking {
    // Main thread
    println("Main thread: ${Thread.currentThread().name}")

    launch(Dispatchers.Default) {
        // Background thread for CPU-intensive work
        println("Background thread: ${Thread.currentThread().name}")
        val result = (1..1_000_000).map { it * 2 }.sum()
        println("Computation result: $result")
    }

    launch(Dispatchers.IO) {
        // I/O thread for blocking operations
        println("IO thread: ${Thread.currentThread().name}")
        Thread.sleep(1000) // Simulate blocking I/O
        println("I/O operation completed")
    }

    delay(2000) // Wait for background work
}

// 4. Structured Concurrency with SupervisorJob
fun structuredConcurrencyExample() = runBlocking {
    val supervisorJob = SupervisorJob()

    with(CoroutineScope(supervisorJob)) {
        launch {
            delay(1000)
            println("Child 1 completed")
            throw Exception("Child 1 failed") // This won't affect other children
        }

        launch {
            delay(1500)
            println("Child 2 completed")
        }

        launch {
            delay(2000)
            println("Child 3 completed")
        }
    }

    println("Parent scope completed")
}

// 5. Coroutine Scopes and Contexts
class UserRepository {
    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)

    suspend fun loadUsers(): List<User> = withContext(Dispatchers.IO) {
        delay(1000)
        (1..5).map {
            User(it.toLong(), "user$it", "[email protected]")
        }
    }

    fun refreshUsers(onComplete: (List<User>) -> Unit) {
        scope.launch {
            val users = loadUsers()
            onComplete(users)
        }
    }

    fun cleanup() {
        scope.cancel()
    }
}

// 6. Channels for Coroutine Communication
fun channelExample() = runBlocking {
    val channel = Channel<Int>(10)

    // Producer coroutine
    val producer = launch {
        for (i in 1..10) {
            channel.send(i)
            println("Sent: $i")
            delay(100)
        }
        channel.close()
    }

    // Consumer coroutine
    val consumer = launch {
        for (value in channel) {
            println("Received: $value")
            delay(150)
        }
    }

    producer.join()
    consumer.join()
}

// 7. Actor Pattern
sealed class CounterMessage {
    object Increment : CounterMessage()
    object Decrement : CounterMessage()
    class GetValue(val response: CompletableDeferred<Int>) : CounterMessage()
}

fun actorExample() = runBlocking {
    val counterActor = actor<CounterMessage>(Dispatchers.Default) {
        var counter = 0
        for (message in channel) {
            when (message) {
                is CounterMessage.Increment -> counter++
                is CounterMessage.Decrement -> counter--
                is CounterMessage.GetValue -> message.response.complete(counter)
            }
        }
    }

    // Send messages to actor
    repeat(5) {
        counterActor.send(CounterMessage.Increment)
    }

    // Get value from actor
    val response = CompletableDeferred<Int>()
    counterActor.send(CounterMessage.GetValue(response))
    val value = response.await()

    println("Counter value: $value")
    counterActor.close()
}

// 8. Flow for Reactive Streams
fun flowExample() = runBlocking {
    val flow = flow {
        for (i in 1..10) {
            delay(100)
            emit(i)
        }
    }

    flow
        .filter { it % 2 == 0 }
        .map { it * it }
        .collect { value ->
            println("Collected: $value")
        }
}

// 9. StateFlow and SharedFlow
class NewsRepository {
    private val _news = MutableStateFlow("No news yet")
    val news: StateFlow<String> = _news

    private val _updates = MutableSharedFlow<String>()
    val updates: SharedFlow<String> = _updates

    suspend fun fetchLatestNews() {
        delay(1000)
        _news.value = "Breaking: Kotlin coroutines are awesome!"
        _updates.emit("News updated at ${System.currentTimeMillis()}")
    }
}

fun stateFlowExample() = runBlocking {
    val repository = NewsRepository()

    // Collect news updates
    val newsJob = launch {
        repository.news.collect { news ->
            println("News update: $news")
        }
    }

    // Collect specific updates
    val updatesJob = launch {
        repository.updates.collect { update ->
            println("Update: $update")
        }
    }

    // Simulate multiple news updates
    repeat(3) {
        delay(1500)
        repository.fetchLatestNews()
    }

    delay(500)
    newsJob.cancel()
    updatesJob.cancel()
}

// 10. Coroutine Exception Handling
fun exceptionHandlingExample() = runBlocking {
    val handler = CoroutineExceptionHandler { _, exception ->
        println("Caught ${exception::class.simpleName}: ${exception.message}")
    }

    val job = launch(handler) {
        println("About to throw exception")
        throw RuntimeException("Something went wrong!")
    }

    job.join()

    // Exception handling with try-catch
    try {
        val result = async {
            delay(500)
            throw IllegalArgumentException("Invalid argument")
        }.await()
    } catch (e: Exception) {
        println("Caught exception: ${e.message}")
    }
}

// 11. Parallel Processing with Coroutines
suspend fun processDataInParallel(data: List<Int>): List<Int> = coroutineScope {
    val chunkSize = 100
    val chunks = data.chunked(chunkSize)

    chunks.map { chunk ->
        async(Dispatchers.Default) {
            chunk.map { it * 2 }
        }
    }.awaitAll().flatten()
}

fun parallelProcessingExample() = runBlocking {
    val data = (1..1000).toList()

    val time = measureTimeMillis {
        val result = processDataInParallel(data)
        println("Processed ${result.size} items")
    }

    println("Parallel processing took: $time ms")
}

// 12. Debounce and Throttle Operators
fun debounceThrottleExample() = runBlocking {
    val events = MutableSharedFlow<Int>()

    // Debounce operator
    val debouncedFlow = events
        .debounce(300)
        .onEach { println("Debounced: $it") }
        .launchIn(this)

    // Throttle operator
    val throttledFlow = events
        .sample(200)
        .onEach { println("Throttled: $it") }
        .launchIn(this)

    // Emit events rapidly
    repeat(10) { i ->
        delay(100)
        events.emit(i)
    }

    delay(1000)
}

// 13. Retry Mechanism
suspend fun <T> retry(
    times: Int = 3,
    initialDelayMillis: Long = 100,
    factor: Double = 2.0,
    block: suspend () -> T
): T {
    var currentDelay = initialDelayMillis
    repeat(times - 1) {
        try {
            return block()
        } catch (e: Exception) {
            println("Attempt failed: ${e.message}. Retrying in ${currentDelay}ms")
            delay(currentDelay)
            currentDelay = (currentDelay * factor).toLong()
        }
    }
    return block() // Last attempt
}

fun retryExample() = runBlocking {
    var attempts = 0
    val result = retry(times = 3) {
        attempts++
        if (attempts < 3) {
            throw RuntimeException("Simulated failure")
        }
        "Success after $attempts attempts"
    }

    println(result)
}

// 14. Coroutine Timeout
fun timeoutExample() = runBlocking {
    try {
        withTimeout(1000) {
            delay(2000) // This will timeout
            "This won't be reached"
        }
    } catch (e: TimeoutCancellationException) {
        println("Operation timed out: ${e.message}")
    }

    try {
        val result = withTimeoutOrNull(1500) {
            delay(1000) // This will succeed
            "Operation completed successfully"
        }
        println("Result: \$result")
    } catch (e: Exception) {
        println("Unexpected error: ${e.message}")
    }
}

// 15. Coroutine Worker Pool
class WorkerPool(private val poolSize: Int) {
    private val job = SupervisorJob()
    private val dispatcher = Dispatchers.Default.limitedParallelism(poolSize)
    private val channel = Channel<suspend () -> Unit>(Channel.UNLIMITED)

    init {
        repeat(poolSize) {
            launch(dispatcher) {
                for (task in channel) {
                    try {
                        task()
                    } catch (e: Exception) {
                        println("Worker error: ${e.message}")
                    }
                }
            }
        }
    }

    suspend fun execute(task: suspend () -> Unit) {
        channel.send(task)
    }

    fun shutdown() {
        job.cancel()
        channel.close()
    }
}

fun workerPoolExample() = runBlocking {
    val pool = WorkerPool(3)

    repeat(10) { i ->
        pool.execute {
            delay(Random.nextLong(100, 500))
            println("Task $i completed by ${Thread.currentThread().name}")
        }
    }

    delay(3000)
    pool.shutdown()
}

// Main function demonstrating all coroutine examples
fun main() {
    println("=== Kotlin Coroutines Examples ===
")

    // Basic examples
    println("1. Basic Coroutine:")
    basicCoroutineExample()

    println("
2. Async/Await:")
    asyncAwaitExample()

    println("
3. Dispatchers:")
    dispatchersExample()

    println("
4. Structured Concurrency:")
    structuredConcurrencyExample()

    println("
5. Channel Communication:")
    channelExample()

    println("
6. Actor Pattern:")
    actorExample()

    println("
7. Flow Reactive Streams:")
    flowExample()

    println("
8. StateFlow and SharedFlow:")
    stateFlowExample()

    println("
9. Exception Handling:")
    exceptionHandlingExample()

    println("
10. Parallel Processing:")
    parallelProcessingExample()

    println("
11. Debounce and Throttle:")
    debounceThrottleExample()

    println("
12. Retry Mechanism:")
    retryExample()

    println("
13. Timeout:")
    timeoutExample()

    println("
14. Worker Pool:")
    workerPoolExample()

    println("
=== Coroutines Examples Completed ===")
}

工具

经常与该案例搭配使用的工具

相关内容

相关案例集合

工具使用指南

帮助搜索与理解工作流的案例说明

标题

Kotlin 示例

描述

基础Kotlin代码示例,包括Android开发、JVM后端和现代Kotlin特性

概览

基础Kotlin代码示例,包括Android开发、JVM后端和现代Kotlin特性

适用场景

  • Use this sample set when you want reference inputs for Kotlin 示例.
  • Use it to preview output formats and compare related sample variants.

使用方式

  1. 1Open a sample entry to inspect the prepared example payload or asset.
  2. 2Compare it with related tools to understand how the workflow connects.

常见用途

  • Kotlin Hello World
  • Kotlin 面向对象编程
  • Kotlin 协程与并发

常见问题

What is included in Kotlin 示例?

This page includes curated sample entries, related tools, and neighboring sample collections for Kotlin 示例.

首页
工具3197
案例593
可视化461
文件查看器103
专题229
标签333
图像、音频与视频655

图像、音频、视频处理、转换与优化工具

数学、日期与金融644

计算器、数值计算、日期逻辑、统计与金融工具

设计与颜色296

颜色、版式、图形、视觉样式与设计辅助工具

文本与写作209

写作、清洗、格式化、提取与文本分析工具

开发与 Web193

开发者工具、网络处理、Web 调试与自动化辅助工具

转换与编码175

格式、文件、压缩包、单位与编码转换工具

界面截图结构化、人工校对与开发交付
钢琴旋律草稿创作、MIDI 核验与试听样稿交付
复古游戏纹理制作、候选评审与素材交付
操作截图到可复核图文指南与培训交付
网页改版响应式视觉回归审核与证据交付

© 2026 Elysia Tools. 保留所有权利。

文档价格关于我们服务条款隐私政策Cookie 政策联系我们

Development

JSON 转 Kotlin Data Class

将 JSON 数据转换为 Kotlin data class,含 @SerializedName 注解、可空处理与嵌套类型推断

Development

代码格式化器

格式化各种语言的代码

Kotlin

Android Kotlin 移动端功能示例

Android Kotlin 移动端功能示例,包括设备信息、网络状态和振动控制

Kotlin

Android Kotlin 多线程编程示例

Android Kotlin 多线程编程示例,包括线程创建、锁同步和线程池使用

编程语言

Clojure 语言示例

基本的Clojure编程示例,用于JVM上的函数式编程

编程语言

Dart 语言示例

Dart编程示例和Flutter开发基础

编程语言

Lua 语言示例

Lua编程示例,用于游戏开发和嵌入式脚本

编程语言

PHP 示例

基础PHP代码示例,包括Web开发、现代PHP 8+特性和框架