Preface:
In Groovy we can assign default values to parameters in a method. If we define a default value for a parameter Groovy basically supports two method signatures: one with all parameters and one where the parameter with a default value is omitted. If we use multiple parameters with default values then the right most parameter with a default value is first eliminated then the next and so on.
來看範例代碼:
- def say(a = 'a', b = 'b', c, d='d', e) {
- "a=$a b=$b c=$c d=$d e=$e"
- }
- // We can invoke 4 signatures:
- assert 'a=a b=b c=1 d=d e=2' == say('1', '2') // 有多少個未給定預設值的餐數, 最少就需要給多少參數
- // 最後的 2 個參數是給沒有預設參數的參數, 前面的參數會依序給其他有預設值的參數
- assert 'a=1 b=b c=2 d=d e=3' == say('1', '2', '3')
- assert 'a=1 b=2 c=3 d=d e=4' == say('1', '2', '3', '4')
- assert 'a=1 b=2 c=3 d=4 e=5' == say('1', '2', '3', '4', '5')
* User Guide: Extended Guide to Method Signatures
沒有留言:
張貼留言