Home > Blockchain >  How to use the lambda in kotlin ->
How to use the lambda in kotlin ->

Time:12-30

Have a question about -> in kotlin.

   fun test0 (a: String, combine: (b: String) -> String ): String {
        return combine(a)
   }

There is a example function above, how to use this function? I dont know how to pass the parm combine.

Have tried follow:

    private fun getFold(a: String): String {
        return a
    }

    fun test() {
        var a: String = "a"
        val test1 = test0 (a,  combine = getFold(a))
    }

Sync error in combine = getFold(a)) ,say:

Type mismatch. Required:(String) → String Found: String

So how to pass the parm combine?

CodePudding user response:

test0(a, combine = ::getFold)

or

test0(a, combine = this::getFold)

CodePudding user response:

In your example, combine is a parameter of type (b: String) -> String, which is a function taking a single String and returning a String.

(In fact, you don't need to name the parameter b; it could simply be written (String) -> String.)

There are three main ways to pass a function as a parameter:

  1. As a lambda. This is perhaps the most common: you provide the function body directly, in braces. For example:

     val test1 = test0(a, { it })
    

Here the lambda is { it }. (it is a keyword you can use in lambdas which take a single parameter, and refers to that parameter. An equivalent might be { a -> a }.)

  1. As an anonymous function. This is similar to a lambda, but the syntax is more like defining a normal function; it's more verbose, but gives you more control. In this case you could use a normal function body:
val test2 = test0(a, fun(b: String): String { return b })

Or an expression body:

val test2 = test0(a, fun(b: String) = b)
  1. As a callable reference. This is for when you have an existing method or function that you want to use. (You might already have a suitable function in your project, or in a library; or the code might be too long to fit neatly into a lambda.)

It's done using the :: operator, e.g.:

val test3 = test0(a, ::getFold)

You can reference a method, top-level function, extension function, property, or constructor in this way. (If it's not a top-level function, you may need to tell the compiler which object/class it belongs to — just as you would when calling it directly — e.g. myInstance::methodName.)

It looks like this is what the code in the question is trying to do. However, the lambda syntax is usually simpler and clearer, so consider that if you don't need the existing function for any other reason.


(The error message in the question is because combine = getFold(a) will call getFold(), and try to assign its result to the combine parameter. That result is a String, not a function type, hence the type mismatch.)

CodePudding user response:

Or like this:

combine = {getFold(a)}
  • Related