class OptionalExample def main is shared # Instance eg does not send an argument for the constructor's # optional parameter. eg = ExampleClass() assert eg.name =='Default name' eg.exampleMethod(1, "One", 1) assert eg.required ==1 and eg.optionalStr == 'One' and eg.optionalInt ==1 eg.exampleMethod(2, "Two") assert eg.required ==2 and eg.optionalStr == 'Two' and eg.optionalInt ==10 eg.exampleMethod(3) assert eg.required ==3 and eg.optionalStr == 'default' and eg.optionalInt ==10 # Instance eg2 sends an argument for the constructor's optional parameter. eg2 = ExampleClass("Provided name") assert eg2.name =='Provided name' eg2.exampleMethod(1, "One", 1) assert eg2.required ==1 and eg2.optionalStr == 'One' and eg2.optionalInt ==1 eg2.exampleMethod(2, "Two") assert eg2.required ==2 and eg2.optionalStr == 'Two' and eg2.optionalInt ==10 eg2.exampleMethod(3) assert eg2.required ==3 and eg2.optionalStr == 'default' and eg2.optionalInt ==10 # The following statements produce compiler errors. # An argument must be supplied for the first parameter, and it # must be an integer. #eg.exampleMethod("One", 1) #eg.exampleMethod() # You cannot leave a gap in the provided arguments. #eg.exampleMethod(3, ,4) #eg.exampleMethod(3, 4) # You can use a named parameter to make the previous # statement work. #eg.exampleMethod(3, optionalint: 4) class ExampleClass var name as String var required =0 var optionalStr = '' var optionalInt =0 cue init(name as String = "Default name") base.init .name = name # The first parameter, required, has no default value assigned # to it. Therefore, it is not optional. Both optionalstr and # optionalint have default values assigned to them. They are optional. def exampleMethod(required as int, optionalstr as String = "default", optionalint as int = 10) #print String.format("{0}: {1}, {2}, and {3}.", .name, required, optionalstr, optionalint) .required = required .optionalStr = optionalstr .optionalInt = optionalint