0

I have function which returns some value. In the function parameter I pass the same value:

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

How can I call getValue function in another function? For example:

fun getResult (){
var a = getValue (what here?)
}
2
  • For example with a string literal: var a = getValue ("Hello"). Also note that the assignment value = "Hello" inside the getValue function is useless. What did you intend to achieve? Commented Dec 28, 2020 at 9:20
  • But when I call getValue method I need in resalt var a = message Commented Dec 28, 2020 at 9:25

1 Answer 1

1

You can pass a function as a prameter for another function in kotlin. Kotlin functions can take other functions in arguments, or even return them.

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

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

and call getResult and pass function to it:

getResult({  getValue("Hello") })
Sign up to request clarification or add additional context in comments.

4 Comments

in this case here getResult(getValue("Hello")) I get error: Type mismatch. Required: (String) → String Found: String
@Julia Sorry , I edit and test my answer. Please try again.
but for example I get in message' (getValue` method) "DDD" value. How can I do that here var a = func("some string") I get "DDD"too?
@Julia I hope underastand your mean. If you mean return back result from getResult() function, e.g. a value, do like other function. It's enough to change type of return back in getResult() function. easily change to: fun getResult (func:(String) -> String):String { //TODO return a}. If my answer can help you and is correct, please accept it. Thanks tou if upvote useful comments too. Good Luck.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.