Reputation: 2393
I'm a Kotlin beginner, eager to know about the behaviour of the lambda expression for println.unfortunately both functions are doing same job.
val printFunction1:(String) -> Unit = {
println("Hello, $it!")
}
val printFunction2 = {
user: String ->
println("Hello, $user!")
}
I can call the functions like this, It would be good if someone can explain this.
printFunction1("Bini")
printFunction2("Jenu")
Upvotes: 0
Views: 94
Reputation: 82087
What would you expect the functions to behave like?
The first one has an explicit function type (String) -> Unit
. That way, you don't need to specify the argument type String
inside the lambda. You can just use it
(implicit name for single arguments of lambdas) as a String
.
The second one does not specify a type and you need to tell the compiler what type your lambda parameter has, which you did with user: String ->
. Note that it's more idiomatic to move this part to the line with the opening bracket:
val printFunction2 = { user: String ->
println("Hello, $user!")
}
Otherwise I don't see anything fancy going on here. Let me know if you need further clarification.
Upvotes: 1
Reputation: 134
Lambdas behave exactly like normal functions do in both cases. accept input(parameter) as string and the function executes println() Normal function:
fun funName(parameters):ReturnType{FunBody}
Lambda function tied to variable:
var varFunName:(ParameterType) ->Unit={FunBody}
or
var varFunName = {
parameters -> {FunBody}
}
Note: since there is no parameter name in the first type it automatically maps to it variable/expression for more understanding do look at grammar for functionLiterals the page does have grammar for all Kotlin language constructs might need some amount of time to get to understand all grammars are links so if you want to understand that part just follow the link
Upvotes: 1