For example I want to filter object by some field values. I can write
objects.filter{ o =>
val set = Set(c1,c2)
set contains o.field
}
in that case I will create hashset each time method called ==> it will be slow
I also can write this way
val set = Set(c1,c2)
objects.filter{ o =>
set contains o.field
}
It will work fast but I pollute my space with meaningless object set
.
What is the best way to do this?
This seems to work:
objects.filter {
val set = Set(c1,c2)
o => set contains o.field
}
If you will factor out "Set(c1,c2)" into a def like this:
def getSet = { println("Set!"); Set(5,7)}
You would see that there is only one set created.
Just put braces around it, and namespace is no longer polluted.
{
val set = Set(c1,c2)
objects.filter{ o =>
set contains o.field
}
}
Use inner named functions, they help better structure the code and keep namespace clean.
def someMeaningfulName = {
val set = Set(c1,c2)
objects.filter{ o =>
set contains o.field
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With