Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
use closures as functions
@GrabResolver('https://oss.sonatype.org/content/groups/public')
@Grab('org.functionaljava:functionaljava:4.2')
import fj.F2
import groovy.transform.Canonical
import groovy.transform.Immutable
import groovy.transform.stc.ClosureParams
import groovy.transform.stc.SimpleType
@Canonical
public class CustomerNotifier {
CustomerRepository customerRepository
EmailSender emailSender
String environment
//input parameters of closure are implicit
void notifyWithClosure(CustomerId customerId, Closure<Email> createsEmail) {
def customer = this.customerRepository.getBy(customerId)
def email = createsEmail.call(customer, environment)
this.emailSender.sendEmail(email)
}
//input parameters of closure are defined as closureParams
void notifyWithClosureParams(CustomerId customerId,
@ClosureParams(value = SimpleType.class, options = ["Customer", "String"]) Closure<Email> createsEmail) {
def customer = this.customerRepository.getBy(customerId)
def email = createsEmail.call(customer, environment)
this.emailSender.sendEmail(email)
}
//input parameters of function are explicit
void notifyWithFunction(CustomerId customerId, F2<Customer, String, Email> createsEmail) {
def customer = this.customerRepository.getBy(customerId)
def email = createsEmail.f(customer, environment)
this.emailSender.sendEmail(email)
}
}
interface CustomerRepository {
Customer getBy(CustomerId id)
}
interface EmailSender {
void sendEmail(Email email)
}
@Immutable
class Email {
String to, from, subject, content
}
@Immutable
class Customer {
CustomerId id
String fullname
String emailAddress
}
@Immutable
class CustomerId {
UUID uuid
}
def customerRepository = { CustomerId id -> new Customer(id, "fullname of $id", "email of $id") } as CustomerRepository
def emailSender = {} as EmailSender
def customerNotifier = new CustomerNotifier(customerRepository, emailSender, "development")
def customerId = new CustomerId(UUID.randomUUID())
customerNotifier.notifyWithClosure(customerId) { customer, env ->
new Email(env == 'dev' ? 'phonyEmail@me.com' : customer.emailAddress, "noreply@me.com", 'subject', 'content')
}
customerNotifier.notifyWithClosureParams(customerId) { customer, env ->
new Email(env == 'dev' ? 'phonyEmail@me.com' : customer.emailAddress, "noreply@me.com", 'subject', 'content')
}
customerNotifier.notifyWithFunction(customerId) { customer, env ->
new Email(env == 'dev' ? 'phonyEmail@me.com' : customer.emailAddress, "noreply@me.com", 'subject', 'content')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.