Java (or Groovy) Scala equivalent applies

In Scala, if there is an object Foo

that has apply(x: Int)

, I can call it with Foo(42)

(as shorthand for Foo.apply(42)


Can this be reproduced in Java or Groovy? I thought Groovy call

would function in a similar way, but def call(int x)

neither static def call(int x)

did they callcall

EDIT : adding example DSL as requested

Typical / existing DSL: alter 't' add 'a' storing BAR

(where BAR

is an enumeration). Trying to add something that will replace BAR

in the above but will accept an argument but not much different from the syntax, ideally:alter 't' add 'a' storing FOO(42)

I created FOO as a class with a constructor that takes an int - what I'm looking for now is a way to call that constructor Foo(42)

instead of new FOO(42)


source to share

2 answers

The straightforward way in Groovy would be to write a method static call()

for the class, but it doesn't do the job Clazz()

. It might be a bug, but I couldn't find JIRA about it.

I would like to suggest using a closure:

import groovy.transform.Canonical as C

@C class Bar { def bar }

@C class Baz { def baz }

A = { new Bar(bar: it) }

B = { new Baz(baz: it) }

assert A("wot") == new Bar(bar: "wot")
assert B("fuzz") == new Baz(baz: "fuzz")


Update : It looks like the class name is resolved as a static method call in the callee context, this works (but not used in DSL):

class A { 
    static call(str) { str.toUpperCase() } 
assert ((Class)A)("qwop") == "QWOP"


Update 2: As per your DSL example, is it possible to remove partners?

class FOO {}

def params = [:]

alter = { 
  params.alter = it
  [add : { 
      params.add = it
      [storing: { 
          params.clazz = it
          [:].withDefault { params.param = it }

alter 't' add 'a' storing FOO 42

assert params == [
  alter : 't',
  add   : 'a',
  clazz : FOO,
  param : '42'





Groovy has a method call()

that can be omitted:

def action = { a, b = 1 -> println "$a and $b" } 1 // prints "1 and 1"
action( 1, 3 ) // prints "1 and 3"


In Java, the closest alternative is Runnable

: it provides no-arg run()

, but cannot be short



All Articles