when to use an inline function in Kotlin?

后端 未结 5 366
借酒劲吻你
借酒劲吻你 2020-12-04 05:50

I know that an inline function will maybe improve performance & cause the generated code to grow, but I\'m not sure when it is correct to use one.

lock(l         


        
5条回答
  •  臣服心动
    2020-12-04 06:21

    One simple case where you might want one is when you create a util function that takes in a suspend block. Consider this.

    fun timer(block: () -> Unit) {
        // stuff
        block()
        //stuff
    }
    
    fun logic() { }
    
    suspend fun asyncLogic() { }
    
    fun main() {
        timer { logic() }
    
        // This is an error
        timer { asyncLogic() }
    }
    

    In this case, our timer won't accept suspend functions. To solve it, you might be tempted to make it suspend as well

    suspend fun timer(block: suspend () -> Unit) {
        // stuff
        block()
        // stuff
    }
    

    But then it can only be used from coroutines/suspend functions itself. Then you'll end up making an async version and a non-async version of these utils. The problem goes away if you make it inline.

    inline fun timer(block: () -> Unit) {
        // stuff
        block()
        // stuff
    }
    
    fun main() {
        // timer can be used from anywhere now
        timer { logic() }
    
        launch {
            timer { asyncLogic() }
        }
    }
    

    Here is a kotlin playground with the error state. Make the timer inline to solve it.

提交回复
热议问题