precomputing some code in a scala closure. -
in scala, have following code:
def isdifferentgroup(artifact2: defaultartifact) = getartifact(artifact1id).getgroupid != artifact2.getgroupid val artifacts = getartifacts().filter(issamegroup)
the function isdifferentgroup
accessing external string variable artifactid
(closure).
i'd avoid computing getartifact(artifactid)
each item in list.
i follows:
val artifact1: defaultartifact = getartifact(artifact1id) def isdifferentgroup(artifact2: defaultartifact) = artifact1.getgroupid != artifact2.getgroupid val artifacts = getartifacts().filter(issamegroup)
however, creating variable artifact1
outside fonction isdifferentgroup
, , ugly, because variable used inside fonction isdifferentgroup
.
how solve it?
one possibility make partial function follows:
def isdifferentgroup(artifact1: defaultartifact)(artifact2: defaultartifact) = artifact1.getgroupid != artifact2.getgroupid val artifacts = getartifacts().filter(isdifferentgroup(getartifact(artifact1id)))
however, have move code getartifact(artifactid)
outside isdifferentgroup
function, , don't want this.
how solve it?
everything processed in function body evaluated every time function called, can't tell part of statically evaluated , shared (without resorting using kind of external cache). have separate function body values want evaluate in advance , use inside function.
however, can enclose such values in block forms compact block. best thing can think of declare val
function type, such as
val isdifferentgroup: defaultartifact => boolean = { val gid = getartifact(artifact1id).getgroupid (artifact2: defaultartifact) => { (gid != artifact2.getgroupid) } }
this way, can explicitly state part evaluated statically once in main val
block (here gid
) , part evaluated in response artifact2
argument. , can call isdifferentgroup
if method:
println(isdifferentgroup(someartifact))
this different way of creating encapsulating class like
val isdifferentgroup: defaultartifact => boolean = new function1[defaultartifact,boolean] { val gid = getartifact(artifact1id).getgroupid override def apply(artifact2: defaultartifact): boolean = (gid != artifact2.getgroupid); }
you can declare lazy val
, in case gid
evalauted at most once, first time function called.
Comments
Post a Comment