Varargs method parameter
| Code | |
|---|---|
| Result | Winner: 34 |
| Code | |
|---|---|
| Result | Winner: 34 Winner: 31 7 Winner: 2 8 5 |
-
Similar code in multiply overloaded methods.
-
Tedious: Each added argument requires adding another method.
Objective: Get rid of boilerplate code!
| Code | |
|---|---|
| Result | Winner: 1 2 3 4 5 6 7 8 9 |
| Code | |
|---|---|
| Result | Winner: 1 2 3 4 5 6 7 8 9 Winner: 20 19 18 17 16 15 |
-
Only one varargs parameter per method.
-
Must be a method's last argument.
- Video
- Text
-
-
The
varargssection in chapter 4 of [Kurniawan].
No. 147
Creating a flexible max(...) method.
|
Q: |
Get inspired by
|
||||
|
A: |
The varargs mechanism allows for defining: |
No. 148
Enforcing mandatory arguments
|
Q: |
As part of its contract being stated by the
Unfortunately this error does not show up at compile-time but sadly not until run-time and may thus represent a hidden flaw. Question: Why can't we solve this issue by just changing the implementation? Instead modify:
|
||||
|
A: |
By its signature the Changing both our method's signature and implementation is the way to go: Now a minimum of two arguments is being required. Violation yields a compile-time rather than a (sometimes too late) run-time error:
|
