#1437 Cause of it-block constraints?

tonsky Fri 4 Mar 2011

First, I cannot use return inside the it-block — why?

Second, I cannot name closure param it — what’s wrong with it?

My use-case is the following: to quickly modify it-block (adding temporary logging to it, for example), but I cannot do that without renaming it to el or smth.

So, this:

list.map {
  [it.arg1, it.arg2, it.arg3]
}

cannot be easily converted to this:

list.map {
  log.debug('${it.arg1}, ${it.arg2}, ${it.arg3}')
  return [it.arg1, it.arg2, it.arg3]
}

Now I have to made it a proper closure with named param, which can involve a lot of typing:

list.map |ListElType el->Obj?| {
  log.debug('${el.arg1}, ${el.arg2}, ${el.arg3}')
  return [el.arg1, el.arg2, el.arg3]
}

brian Fri 4 Mar 2011

The answer to both your questions is that it was a compromise to prevent it-block closures from being "abused" as control structures. It was debated quite a bit:

  1. only it-blocks should be able to omit the |...| function tokens
  2. it-blocks should be encouraged to used for declarative stuff, not flow-control

I certainly sometimes wish I could take functional route and make return optional and just say last expression is returned. But Fantom is still statement oriented versus expression oriented. Plus personally I think our current rules while slighly annoying, do help to make code more approachable.

Also remember that you can use type inference in your closures, so what your code would really look like is:

list.map |e| {
  log.debug('${e.arg1}, ${e.arg2}, ${e.arg3}')
  return [e.arg1, e.arg2, e.arg3]
} 

A bit more verbose, but not bad compared to it-block syntax is it?

tonsky Sat 5 Mar 2011

Thanks, brian! But why to disallow it as closure param name?

brian Sat 5 Mar 2011

Thanks, brian! But why to disallow it as closure param name?

I guess it doesn't have to be that way, but essentially I think it is the same reason we wouldn't let you name a method parameter this - its sort of a special thing with special scope resolution rules.

panicdotal Sat 5 Mar 2011

I would be in favor of allowing it as a closure param name.

Login or Signup to reply.