named parameters with default values in groovy

浪尽此生 提交于 2019-12-03 22:16:39

Groovy does that for you by default (map constructor). You would not need a factory method. Here is an example

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's astrology :). In case the class is not accessible to set default values, you can do like

@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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!