Kotlin - apply, let, run, also, takeIf

apply: return current receiver once anonymous function complete
package examples

fun main() {
    plus(1,2).apply {
        println(this) // 3
        println(toDouble()) // 3.0
    }
}

fun plus(a: Int, b: Int): Int {
    return a + b
}

let: pass receiver to lambda you provided
package examples

fun main() {
    plus(1,2)?.let { println(it) }
}

fun plus(a: Int, b: Int): Int? {
    return a + b
}

run: Pass execution value. 
package examples

fun main() {
    val grade = 59
    grade.run(::isPassed)
            .run(::comment)
            .run(::println)
}

fun comment(passed:Boolean):String {
    if (passed) {
        return "Good job"
    } else {
        return "Oh no"
    }
}

fun isPassed(grade: Int): Boolean {
    return grade >= 60
}

also: similar to "let" with more side effect
package examples

fun main() {
    val grade = 59
    grade.run(::isPassed)
            .run{comment(this, "QQ")}
            .also(::println)
        .also{ println("$it again") }
}

fun comment(passed:Boolean, suffix:String):String {
    if (passed) {
        return "Good job$suffix"
    } else {
        return "Oh no$suffix"
    }
}

fun isPassed(grade: Int): Boolean {
    return grade >= 60
}

takeIf: Provide predicate to decide will run or not
package examples

fun main() {
    60.takeIf { isPassed(it) }?.run { println("Good Job") }
}

fun isPassed(grade: Int): Boolean {
    return grade >= 60
}


沒有留言:

張貼留言

Lessons Learned While Benchmarking vLLM with GPU

Recently, I benchmarked vLLM on a GPU to better understand how much throughput can realistically be expected in an LLM serving setup. One ...