Groovy是否可以使用默认值命名参数?我的计划是建立一种对象工厂,可以完全不带任何参数地对其进行调用,以获取具有默认值的对象。另外,我需要功能来显式设置对象的任何参数。我相信例如可以使用Python关键字参数。

我现在尝试使用的代码如下所示

// Factory method
def createFoo( name='John Doe', age=51, address='High Street 11') {
  return new Foo( name, age, address )
}

// Calls
Foo foo1 = createFoo()  // Create Foo with default values
Foo foo2 = createFoo( age:21 )  // Create Foo where age param differs from defaut
Foo foo3 = createFoo( name:'Jane', address:'Low Street 11' )  // You get the picture
// + any other combination available

我正在使用的实际应用程序将具有更多的参数,因此需要更多的组合。

谢谢

更新:

我计划的工厂方法用于测试目的。无法真正触摸实际的Foo类,尤其是它不是默认值。

下面的@dmahapatro和@codelarks回答对将Map用作参数的观点很有意义,这使我有了一个可能的解决方案。我可以创建具有所需默认值的 map ,并覆盖所需的值,然后将其传递给工厂方法。除非我得到更好的方法的提示,否则这可能会完成工作,我会继续做下去。

我目前的做法如下
defaults = [ name:'john', age:61, address:'High Street']

@ToString(includeFields = true, includeNames = true)
class Foo {
  // Can't touch this :)
  def name = ''
  def age = 0
  def address = ''
}

def createFoo( Map params ) {
  return new Foo( params )
}

println createFoo( defaults )
println createFoo( defaults << [age:21] )
println createFoo( defaults << [ name:'Jane', address:'Low Street'] )

注意: leftShift操作(<

最佳答案

Groovy默认情况下会为您执行此操作( map 构造函数)。您不需要工厂方法。这是一个例子

import groovy.transform.ToString

@ToString(includeFields = true, includeNames = true)
class Foo{
    String name = "Default Name"
    int age = 25
    String address = "Default Address"
}

println new Foo()
println new Foo(name: "John Doe")
println new Foo(name: "Max Payne", age: 30)
println new Foo(name: "John Miller", age: 40, address: "Omaha Beach")

//Prints
Foo(name:Default Name, age:25, address:Default Address)
Foo(name:John Doe, age:25, address:Default Address)
Foo(name:Max Payne, age:30, address:Default Address)
Foo(name:John Miller, age:40, address:Omaha Beach)

更新
@codelark的占星术:)。如果无法访问该类以设置默认值,则可以执行以下操作
@ToString(includeFields = true, includeNames = true)
class Bar{
    String name
    int age
    String address
}

def createBar(Map map = [:]){
    def defaultMap = [name:'John Doe',age:51,address:'High Street 11']
    new Bar(defaultMap << map)
}

println createBar()
println createBar(name: "Ethan Hunt")
println createBar(name: "Max Payne", age: 30)
println createBar(name: "John Miller", age: 40, address: "Omaha Beach")


//Prints
Bar(name:John Doe, age:51, address:High Street 11)
Bar(name:Ethan Hunt, age:51, address:High Street 11)
Bar(name:Max Payne, age:30, address:High Street 11)
Bar(name:John Miller, age:40, address:Omaha Beach)

关于groovy - groovy中具有默认值的命名参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18001965/

10-17 02:25