首页 > 解决方案 > 如何在kotlin的另一个函数中调用带有参数的函数

问题描述

我有返回一些值的函数。在函数参数中,我传递了相同的值:

 fun getValue (value:String):String {
        var message = value
        value = "Hello"
        return message
    }

如何getValue在另一个函数中调用函数?例如:

fun getResult (){
var a = getValue (what here?)
}

标签: androidkotlin

解决方案


您可以将函数作为参数传递给 kotlin 中的另一个函数。Kotlin 函数可以在参数中接受其他函数,甚至返回它们。

fun getResult (func:(String) -> String) {
        //some code
        var a = func("some string")
    }

    fun getValue (value:String):String {
        var message = value
        return message
    }

并调用 getResult 并将函数传递给它:

getResult({  getValue("Hello") })

推荐阅读