命名参数

问题描述 投票:0回答:6

我有方法

def test(String a, String b) { }

我想用动态参数映射来调用它。 我一直这么认为

test(['1','2']); //valid call

还有

test([a:'1',b:'2']); //=> does not work

会起作用的。但事实并非如此。所以我记得扩展运算符,但无法让它工作......

有没有一种方法可以使用某种映射作为参数而不是单个参数来调用上面的方法?

groovy named-parameters
6个回答
47
投票

方法调用应该是

test(a: '1', b: '2')
而不是
test([a: '1', b: '2'])

请检查文档中的命名参数部分以了解方法


34
投票

也许我错过了一些东西,但我认为 Groovy 现在还没有命名参数。有讨论提案,但我不知道任何官方消息。

对于你的情况,我认为地图传播可能有帮助,但并非在所有情况下都有帮助。获取值后,它遵循声明地图值的顺序:

def test(String a, String b) { "a=$a, b=$b" }
def test(Map m) { test m*.value }

assert test(a: "aa", b:"bb") == "a=aa, b=bb"
assert test(b: "aa", a:"bb") != "a=aa, b=bb" // should be false :-(
assert test(b: "ccc", a:"ddd") == "a=ddd, b=ccc" // should have worked :-(

对于课程,我可以建议 Groovy 的 as 运算符

@groovy.transform.CompileStatic
class Spread {
  class Person {
    String name
    BigDecimal height
  }

  def method(Person p) {
    "Name: ${p.name}, height: ${p.height}"
  }

  def method(Map m) { method m as Person }

  static main(String[] args) {
    assert new Spread().method(name: "John", height: 1.80) == 
      "Name: John, height: 1.80"
  }
}

30
投票

命名参数支持非常灵活,但文档有点薄。以下是我发现的一些规则。 请注意,我试图明确使用术语“参数”(在方法中声明)和“参数”(传递给方法调用)

  • 首先必须声明Map参数。 这是最重要的。而且不明显。
  • 您的参数中不需要完整的 Map,只需要 Map 元素 即
    (a: "aa")
    已经足够好了,你不需要
    ([a: "aa"])
  • 您可以将有序(未命名)参数与名称参数混合,只要 因为有序的 args 保持与参数相同的顺序 他们充满了
  • 您可以将命名参数与常规有序参数散布。 这很酷,但同样,有序参数必须在, 嗯,下单吧。
  • 您甚至可以在同一个中使用可选的有序参数 方法签名(请参阅下面示例中的
    x
  • 你可以给Map参数一个默认的空地图
    args=[:]
    命名参数是可选的,但是如果你有的话,这不能很好地工作 其他可选参数(请参阅下面的最后一个示例)

以下是一些示例: 参数不需要输入,但为了清楚起见,我添加了类型。

// this method has a map args to capture all named args
// and non-named (ordered) args String s, int n, and int x
// x has a default value so is optional
// the map (here untyped) to capture the nameed args MUST COME FIRST
def m(Map args=[:], String s, int n, int x=1)
{
    println "s:$s n:$n x:$x, args:$args"
}

//1: pass in named args first, then ordered
m(a: "aa", b: 3, "ss", 44, 5) // s:ss n:44 x:5, args:[a:aa, b:3]

//2:  ordered args first -  named args last (same result)
m("ss", 44, 5, a: "aa", b: 3) // s:ss n:44 x:5, args:[a:aa, b:3]

//3:  bring the first ordered arg (s) to the start (same result)
m("ss", a: "aa", b: 3, 44, 5) // s:ss n:44 x:5, args:[a:aa, b:3]

//4: stick the ordered arg n in the middle of the named args (same result!)
m("ss", a: "aa", 44, b: 3, 5) // s:ss n:44 x:5, args:[a:aa, b:3]


//5:  mix the ordered args in with the named and SKIP the arg x with default value (x=1)
m(a: "aa", "ss", b: 3, 44) // s:ss n:44 x:1, args:[a:aa, b:3] 

//6: ordered arg n first - so in the wrong order (Fail!)
//m(44, "ss", a: "aa", b: 3, 5) //MissingMethodException: No signature .. of .. m() .. applicable for 
                             // argument types: (java.util.LinkedHashMap, java.lang.Integer, java.lang.String, java.lang.Integer)
                             // values: [[a:aa, b:3], 44, ss, 5]

//7:  no named args: Fails! (change signature to add default: Map args=[:] and it will succeed with: s:ss n:44 x:1, args:[:]
m("ss", 44) // ...No signature ... applicaple ... types (java.lang.String, java.lang.Integer)

//8: no named args: Fails! (even with default map in signature this fails!)
m("ss", 44, 5) // ...No signature ... applicaple ... types (java.lang.String, java.lang.Integer, java.lang.Integer)

9
投票

我非常讨厌 groovy 处理位置和命名/默认参数的方式。它是可怕的。毫无疑问,Python 做得正确。

问题

  1. 使用参数名称调用函数实际上会创建一个映射并使该映射成为第一个参数。

代码

test(a:"a", b: "b") // Actual myfunc([a: "a", b: "b"])
test("a", b: "b")  // Actual myfunc([b: "b"], "a")
test(a: "a", "b")  // Actual myfunc([a: "a"], "b")

这很糟糕,因为它实际上改变了位置参数的顺序。

  1. 普通的默认参数不能乱序调用

代码

def test(String a, String b, int x=1, int y=2){
  a = args.get('a', a)
  b = args.get('b', b)
  x = args.get('x', x)
  y = args.get('y', y)

  println "a:$a b:$b x:$x, y:$y"
}

test("a", 'b')  // Positional arguments without giving the default values
// "a:a b:b x:1 y:2"

test("a", "b", 3)  // Positional arguments with giving 1 default and not the last
// "a:a b:b x:3 y:2"

test("a", "b", y:4)  // Positional with Keyword arguments. Actual call test([y:4], "a", "b")
// This fails!? No signature of method, because Map is the first argument

当然,您始终可以重写该函数以使参数与您想要的位置匹配。当你有很多争论时,这只是一个巨大的麻烦。

  1. 使用 Map 作为第一个参数不允许纯位置参数

代码

def test1(Map args=[:], String a, String b, int x=1, int y=2){
  a = args.get('a', a)
  b = args.get('b', b)
  x = args.get('x', x)
  y = args.get('y', y)

  println "test1(a:$a b:$b x:$x, y:$y, args:$args)"
}

test1("ss", "44", 5, c: "c", d: 3)  // Actual test2([c: "c", d: 3], "ss", "44", 5) Matches our definition
// test1(a:ss b:44 x:5, y:2, args:[c:c, d:3, a:ss, b:44, x:5, y:2])

test1(a: "aa", b: 3, "ss", "44", 5)  // Actual test2([a: "aa", b: 3], "ss", "44", 5) Nothing wrong with repeat parameters because they are in the map
// test1(a:aa b:3 x:5, y:2, args:[a:aa, b:3, x:5, y:2])

test1(a: "aa", b: 3, "ss", "44", y:5)  // Actual test2([a: "aa", b: 3, y:5], "ss", "44") y is in the map, so y still has the default positional value
// test1(a:aa b:3 x:1, y:5, args:[a:aa, b:3, y:5, x:1])

test1("ss", "44", y:3)  // Actual test2([y:3], "ss", "44")
// test1(a:ss b:44 x:1, y:3, args:[y:3, a:ss, b:44, x:1])

test1('a', 'b')  // Pure positional arguments only required arguments given (no defaults given)
// test1(a:a b:b x:1, y:2, args:[a:a, b:b, x:1, y:2])

test1("ss", "44", 5)  // Pure positional arguments one missing
// This fails!? No signature of method. Why?

test1("ss", "44", 5, 6)  // Pure positional arguments all arguments given
// This fails!? No signature of method. Why?

我的解决方案...

最终我的解决方案是接受任意数量的参数作为对象,并使用定义的参数映射来映射这些参数。

代码

// Return a Map of arguments with default values. Error if argument is null
def mapArgs(Object args, Map m){
  Map check = [:]
  def offset = 0

  // Check if first argument is map and set values
  if (args[0] instanceof Map){
    check = args[0]
    offset += 1
    check.each{ subitem ->
      m[subitem.key] = subitem.value
    }
  }

  // Iter positional arguments. Do not replace mapped values as they are primary.
  m.eachWithIndex{ item, i ->
    m[item.key] = ((i + offset) < args.size() && !check.containsKey(item.key)) ? args[i + offset] : item.value
    if (m[item.key] == null){
      throw new IllegalArgumentException("Required positional argument ${item.key}")
    }
  }
  return m
}

def test2(Object... args) {
  // println "args $args"
  def m = mapArgs(args, [a: null, b: null, x: 1, y:2])
  println "test2(a:$m.a b:$m.b x:$m.x, y:$m.y, args:null)"
}

test2("ss", "44", 5, c: "c", d: 3)  // Actual test2([c: "c", d: 3], "ss", "44", 5) Matches our definition
// test1(a:ss b:44 x:5, y:2, args:[c:c, d:3, a:ss, b:44, x:5, y:2])
// test2(a:ss b:44 x:5, y:2, args:null)

test2(a: "aa", b: 3, "ss", "44", 5)  // Actual test2([a: "aa", b: 3], "ss", "44", 5) Nothing wrong with repeat parameters because they are in the map
// test1(a:aa b:3 x:5, y:2, args:[a:aa, b:3, x:5, y:2])
// test2(a:aa b:3 x:5, y:2, args:null)

test2(a: "aa", b: 3, "ss", "44", y:5)  // Actual test2([a: "aa", b: 3, y:5], "ss", "44") y is in the map, so y still has the default positional value
// test1(a:aa b:3 x:1, y:5, args:[a:aa, b:3, y:5, x:1])
// test2(a:aa b:3 x:1, y:5, args:null)

test2("ss", "44", y:3)  // Actual test2([y:3], "ss", "44")
// test1(a:ss b:44 x:1, y:3, args:[y:3, a:ss, b:44, x:1])
// test2(a:ss b:44 x:1, y:3, args:null)

test2('a', 'b')  // Pure positional arguments only required arguments given (no defaults given)
// test1(a:a b:b x:1, y:2, args:[a:a, b:b, x:1, y:2])
// test2(a:a b:b x:1, y:2, args:null)

test2("ss", "44", 5)  // Pure positional arguments one missing
// This fails!? No signature of method. Why?
// test2(a:ss b:44 x:5, y:2, args:null)

test2("ss", "44", 5, 6)  // Pure positional arguments all arguments given
// This fails!? No signature of method. Why?
// test2(a:ss b:44 x:5, y:6, args:null)

我对这个解决方案不太满意,但它使关键字参数满足我的需求。


8
投票

感谢Will P的评论,我找到了适合我的问题的解决方案:

如果我定义一个没有类型的参数,我可以传入各种类型,包括 hashMap。 Groovy 会自动将像

a:'h',b:'i'
这样的构造转换为哈希图

def test(myParams, Integer i) {
    return myParams.a + myParams.b
}

assert test(a:'h',b:'i',5) == test(b:'i',a:'h',5)
assert test([a:'h',b:'i'],5) == test(b:'i',a:'h',5)
test('h','i',5); //still throws an exception

这样,我可以使用单个命名参数,但也可以使用 Map!


1
投票

这个问题让我思考,我想出了一个灵活、有趣(如果不可怕)的解决方案。

这个签名似乎可以接受任何参数的组合:

f(Map m=null, Object... obj)

并且它可以用它们做大部分可预测的事情。

  • 如果您传入任何命名参数(在任何位置),它们都会进入 m
  • 如果你传入位置参数,它们会以正确的顺序进入 obj 。
  • 如果你传入一个地图,它被认为是一个位置参数
  • 如果您没有任何命名参数,则 m 为 null(除非您有地图作为第一个参数,请参见下文)

唯一令人恼火的奇怪之处是您传递地图作为第一个位置参数的情况。

f([a:1], 2) has a map m[a:1] and one obj[0]=2

然而

 f([a:1], b:2)

有一个 [b:2] 的映射 m 和一个 obj[0]= 一个映射 [a:1],所以你无法确定映射 m 是位置映射还是命名参数。

顺便说一句,我不一定推荐任何这些,我会尽可能使用精确的参数(我什至更喜欢显式类型)。在我自己的代码中,有很多次我感到有点困惑,并通过添加一些显式类型来修复问题,但在某些情况下,这可能非常有用。

© www.soinside.com 2019 - 2024. All rights reserved.