Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there are way to create method level constants without namespace polution?

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?

like image 604
yura Avatar asked Feb 24 '12 05:02

yura


3 Answers

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.

like image 155
Rogach Avatar answered Nov 10 '22 03:11

Rogach


Just put braces around it, and namespace is no longer polluted.

{
  val set = Set(c1,c2)
  objects.filter{ o =>
    set contains o.field
  }
}
like image 32
Luigi Plinge Avatar answered Nov 10 '22 02:11

Luigi Plinge


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
  }
}
like image 39
Alexander Azarov Avatar answered Nov 10 '22 01:11

Alexander Azarov