Optional omission of type name with the new keyword
If the type of the object is determined from
the programming context, you can omit the type name entirely in the object
creation expression with the new
keyword.
Warning: Omitting the type name
with the
new keyword is
strongly discouraged in typical code. Omit the type name only for XML
manipulation and dense hierarchical structures with long type names.
Some types imported from XSDs have complex and hard-to-read type names.
The following simple examples demonstrate the concepts, but do not promote
usage of this syntax in simple cases.For example, first declare a variable with an explicit type. Next, assign that variable a new object of that type in a simple assignment statement that omits the type name:
// Declare a variable explicitly with a type.
var s : String
// Create a new empty string.
s = new()
You can also omit the type name if the context is a method argument type:
class SimpleObj {
}
class Test {
function doAction (arg1 : SimpleObj) {
}
}
var t = new Test()
// The type of the argument in the doAction method is predetermined,
// and therefore you can omit the type name if you create a new instance as a method argument.
t.doAction(new())
The following example uses both local variables and class variables:
class Person {
private var _name : String as Name
private var _age : int as Age
}
class Tutoring {
private var _teacher : Person as Teacher
private var _student : Person as Student
}
// Declare a variable as a specific type to omit the type name in the "new" expression
// during assignment to that variable.
var p : Person
var t : Tutoring
p = new() // type name omitted
t = new() // type name omitted
// If a class var or other data property has a declared type, optionally omit the type name.
t.Teacher = new()
t.Student = new()
See also
