In Rails, one could use:
returning Person.create do |p|
p.first_name = "Collin"
p.last_name = "VanDyck"
end
Avoiding having to do this:
person = Person.create
person.first_name = "Collin"
person.last_name = "VanDyck"
person
I think the former way is cleaner and less repetitive. I find myself creating this method in my Scala projects:
def returning[T](value: T)(fn: (T) => Unit) : T = {
fn(value)
value
}
I know that it is of somewhat limited utility due to the tendency of objects to be immutable, but for example working with Lift, using this method on Mapper classes works quite well.
Is there a Scala analog for “returning” that I’m not aware of? Or, is there a similar way to do this in Scala that’s more idiomatic?
Can’t really improve much on what you’ve already written. As you quite correctly pointed out, idiomatic Scala tends to favour immutable objects, so this kind of thing is of limited use.
Plus, as a one-liner it’s really not that painful to implement yourself if you need it!