Reputation: 581
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?
Upvotes: 2
Views: 344
Reputation: 18547
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:
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 }
.)
In fact, because the function parameter is the last parameter, Kotlin lets you move the lambda after the parens:
val test1 = test0(a){ it }
This means exactly the same, but in some cases it can read better (by making the function call look like language syntax; functions like map
and filter
are often called that way).
val test2 = test0(a, fun(b: String): String { return b })
Or an expression body:
val test2 = test0(a, fun(b: String) = b)
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.)
Upvotes: 5
Reputation: 7521
test0(a, combine = ::getFold)
or
test0(a, combine = this::getFold)
Upvotes: 2