在groovy中使用默认值命名参数
在groovy中可以使用默认值命名参数吗?我的计划是制作一种对象工厂,为了获得具有默认值的对象,可以根本不调用任何参数。此外,我需要的功能显式设置对象的任何参数。例如,我相信这对Python关键字参数是可能的。在groovy中使用默认值命名参数
我试图用现在的代码是一样的东西下面
// 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
是我的工作会有的参数有更多的真正的应用程序,从而有更多的组合需要。
感谢
UPDATE:
工厂方法我计划是用于测试目的。无法真正触及实际的Foo类,特别是它不是默认值。
@dmahapatro和@codelarks answere在使用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操作(< <)修改了原来的地图,所以在上面的例子中年龄将是最后的方法调用21为好。在我的情况下,这不是一个问题,因为每次在安装方法中都可以新建默认值映射。
回答:
默认情况下,Groovy会为你做这件事(地图构造函数)。你不需要工厂方法。下面是一个例子
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)
UPDATE
@ 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中使用默认值命名参数 的全部内容, 来源链接: utcz.com/qa/258016.html