Is there a name for this template with closure?

I often see a pattern used in circumstances where we have reverse code that needs to be executed before we can access the object. When using this pattern, it usually begins with a word with.

For example, we have customer records that must be retrieved from the database before we can use them:

def withCustomer (id, closure) {
    def customer = getCustomer(id)
    closure(customer)
}

withCustomer(12345) { customer ->
    println "Found customer $customer.name"
}

Groovy does not make such a distinction between closing or anonymous functions. Perhaps I could ask if there is a name for this template with anonymous functions.

+5
source share
4 answers

. , , . . :

- , (, , )

+4

Groovy Closures - Formal Definition " ".

Groovy , . , Closure, . , :

class SomeCollection {
    public void each ( Closure c )
}

each() :

SomeCollection stuff = new SomeCollection();
stuff.each() { println it }

, , Groovy , :

SomeCollection stuff = new SomeCollection();

stuff.each { println it }       // Look ma, no parens
stuff.each ( { println it } )   // Strictly traditional

, . , Closure :

class SomeCollection {
  public void inject ( x, Closure c )
}

stuff.inject( 0 ) { count, item -> count + item  }     // Groovy
stuff.inject( 0, { count, item -> count + item  } )    // Traditional

"Groovy", , , Scala, "" currying :

scala> def fun[A, B](a: A)(b: B) = {true}
fun: [A, B](a: A)(b: B)Boolean

scala> fun(1){2}
res59: Boolean = true
+2

. (. ). .

. ( ) ( ).

+1

, , .

Loan Pattern, , , .

:

  • "" - Scala
  • - Groovy
+1

All Articles