Returning new session after a non-session setter operation

I never understood the following piece of documentation

.exec(session => {
  // print the Session for debugging, don't do that on real Simulations
  println(session)
  session
})
.exec(session =>
  // session.setAttribute returns the new Session, and Scala automatically returns the last assignment
  // braces are omitted as there's only one instruction
  session.setAttribute("foo", "bar")
)

in

http://gatling.io/docs/1.5.6/user_documentation/reference/session.html

Why is there a “session” after the print statement ? does it return the old session or a new session (in case it is altered just before the print statement ).

If I remove the session after the print statement it says type mismatch error.

Yes, the first example returns the original Session object. If you were to change it before the print, like this:

.exec(session => {
  session.setAttribute("foo", "bar")
  // print the Session for debugging, don't do that on real Simulations
  println(session)
  session
})

It would return the original object, and the changes would be lost, because set() returns a new Session object. If you want to keep the change, you have to do this:

.exec(session => {
  var newSession = session.setAttribute("foo", "bar")
  // print the Session for debugging, don't do that on real Simulations
  println(newSession)
  newSession
})

You can't remove it because then the session function is missing a return matching the return type.

Thanks Michelle

Now I got it. My problem is that the operation before the print statement is an exec(http(“XXXXX”) , had that been a session setter I could have made sure its the last line of the block. Can I assign the output of exec(http(“XXXXX”) , to a session object and return in the last line ?

I’m not sure you even can do that inside a session function. Is there any reason your request can’t be before the session function?

I.e. if you’re trying to do this:

.exec(session => {
  var newSession = exec(http("..."))
  // print the Session for debugging, don't do that on real Simulations
  println(newSession)
  newSession
})

Do this instead:

exec(http("..."))
.exec(session => {
  // print the Session for debugging, don't do that on real Simulations
  println(session)
  session
})

Michelle is right, you can’t do that in a session function, as executing a http request does not return a new session.
Operations altering the session from a http request (e.g. saving the result of a check using saveAs) are handled internally.

But nothing prevents you to do as Michelle suggested : execute the request first and then use a exec taking a session function to print the session’s content if you like.

Yes, I did change my code so that only the session mutation part is in the session function , rest of the code block is outside.

We can close the thread.
Thanks a ton.