Setting two attributes in a single scala function

Hi,

I am trying to set a couple of attributes based on a previously saved attribute. For example, in the following code “adviserCodes” has been saved in a previous findAll:

.exec(session => {
val list = session.getTypedAttributeSeq[String]
session.setAttribute(“adviserCodesJoined”, list.mkString(","))
session.setAttribute(“selectedAdviserCode”, list(random.nextInt(list.size)))
}
)

However, the first value “adviserCodesJoined” is not set, whereas “selectedAdviserCode” is. I presume this has something to do with session immutability, but I’m not sure what’s really going on. Is there any way to make this work? I tried splitting it into two .exec statements and this did work, however I have a more complex example where this would be more quite messy.

Thanks,

Greg.

Hi,

As you suspected, it is related to session immutability.
In your example, the first session.setAttribute(…) creates a new Session, containing the “adviserCodesJoined” attribute. But, since you don’t “save” this new session in a variable, it’s immediately discarded. The “selectedAdviserCode” is correctly set since it’s the last assignement in your function and Scala automatically returns the value produced by the last assignement.

To make it work, you have several options :

  • Chain the setAttributes calls : as setAttribute return a new Session, you can chain setAttribute calls and keep each new attribute you set in session : session.setAttribute(…).setAttribute(…)…

  • If you set only two attributes in your session, save the first session in a val and use this val for the next setAttribute :
    val newSession = session.setAttribute(“adviserCodesJoined”,…)
    newSession.setAttribute(“selectedAdviserCode”,…)

  • If you want to set more than two attributes in your session, use a var and reassign the var each time your create a new Session and return the var when you’ve set everything you want :

var newSession = session
newSession = newSession.setAttribute(…)
newSession = newSession.setAttribute(…)
newSession

Hope this helps you !

Cheers,

Pierre

Pierre,

Thanks, works perfectly - knew it’d be something like this but just couldn’t work out the exact syntax.

Thanks again for your prompt reply,

Greg.

Or, simply:

session.setAttribute(“adviserCodesJoined”, list.mkString(","))
.setAttribute(“selectedAdviserCode”, list(random.nextInt(list.size)))