命名参数

调用 def 时,可以通过名称明确指定参数。这样做意味着无需正确订购。例如,将 printUs() 定义为:

// print out the three arguments in order.
def printUs(one: String, two: String, three: String) = 
   println(s"$one, $two, $three")

现在它可以通过这些方式(以及其他方式)调用:

printUs("one", "two", "three") 
printUs(one="one", two="two", three="three")
printUs("one", two="two", three="three")
printUs(three="three", one="one", two="two") 

这导致在所有情况下都打印出 one, two, three

如果不是所有参数都被命名,则第一个参数按顺序匹配。没有位置(非命名)参数可能跟随命名的参数:

printUs("one", two="two", three="three") // prints 'one, two, three'
printUs(two="two", three="three", "one") // fails to compile: 'positional after named argument'