0

I'd like to write an anonymous lambda function in Kotlin, but it looks like it doesn't take the argument passed to it. (It is not passed at all, since the IDE hints that "variable 'name' is never used".)

Code:

var name = "Tobias Boon"
println("reverse=" + fun(name: String): String {
    var t: String = ""
    for(i in name.indices.last downTo 1) {
        t += text.subSequence(i - 1, i)
    }
    return t
})

Currently prints: reverse=(kotlin.String) -> kotlin.String

4
  • 1
    You arent passing any argument to the function. You are defining a function, and not calling it. Commented Feb 13, 2017 at 12:13
  • I know, I denoted it the description. Commented Feb 13, 2017 at 12:14
  • I've read it. What's the problem then? What is your expected output? Commented Feb 13, 2017 at 12:16
  • I'd like to know how to pass that argument to the lambda... The desired input would be like this would produce println(name.reversed()) Commented Feb 13, 2017 at 12:19

1 Answer 1

5

You never call the function with the parameter, it should be

val name = "Tobias Boon"
println("reverse=" + fun(name: String) : String {
   ...
      return t
}(name))

Btw, your particular example is already implemented in the standard library:

println(name.reversed())
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that was I looking for! "name.reversed()" are you trolling me with this? :)
I know. My intention with this code was to learn about lambdas, not to reverse strings.

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.