0

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")
2
  • 1
    Why do you say "unfortunately" both functions are doing the same job? What exactly did you expect? Commented Nov 23, 2018 at 7:35
  • which one to use actually ? Commented Nov 26, 2018 at 5:30

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

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.