Collection Initializers

A collection initializer uses a shorter syntax to let you make a collection and fill it with an initial set of values. Collection initializers are typically used to make a collection from a set of known values. Examples include the names of months and a list of locations that you can use to validate user input.

The statement New becomes a collection initializer when you start the second line with Begin Call. Then you can supply an optional method name that each initializer calls, which the default is Add. Then you can supply the data.

You write the data items with one of two available constructs. The difference is which separator they use.

The first construct lets you put only one call on a line. Between each argument you put a comma. But the only difference between this and the usual method call is that the method name is missing. Thus, we recommend this construct if the method name or the values are long and/or the method has many parameters.

New SiteList sites
Begin Call
    "Google Search", ""
    "YouTube", ""
    "Facebook", ""
    "Wikipedia", ""

The second construct lets you put many calls on the same line. You write a comma between each value, with all values between braces ({ }). The furst brace must be on the same line after Begin Call and the optional method name. Each value causes a method call with the value as an argument. If the method has more than one parameter, you must use nested braces. Thus, we recommend this construct if the method has a small number of parameters.

New List[String] months
Begin Call {
    "Jan", "Feb", "Mar", "Apr",
    "May", "Jun", "Jul", "Aug",
    "Sep", "Oct", "Nov", "Dec" }

New Map[String, String] states
Begin Call {
    {"AK", "Alaska"}, {"AL", "Alabama"},
    {"AR", "Arkansas"}, {"AZ", "Arizona"},
    {"CA", "California"} /'...'/ }

See also