-
-
Notifications
You must be signed in to change notification settings - Fork 4
constructor
There is a subtle difference between
person{name:"Joe" address{street:"no way 123"}}
person:{name="Joe" address:{street="no way 123"}}
While both construct an object person, the variant with colon constructs pure data while the variant without colon constructs the person via a constructor, if available.
class person{
value{
id=random()
}
}
a=person{} // preferred way
a=person() // works as constructor unless person is a function
By default classes are extendible, so
person{name:"Joe" address{street:"no way 123"}}
works as expected: the person object now has a name field and an id field via the value
constructor.
There are situations where objects are meant to be immutable or non-extendible, or where successful construction depends on the right data at initialization time. These required fields can be denoted via exclamation wasp:
class person{
name!
parent?
address
}
Now every construction person{name:"blah"}
must provide the name argument/field property.
The optional default for class fields is opposite to the function argument defaults, where un-required args can be marked with '?' or with default value.
function log(n, base=10)=…
To avoid senseless redundant constructors, given fields need not be explicitly set by the constructors!!
Instead all data given to the constructor gets matched automatically to the fields (as seen above in person{address=…} )
Only if special logic on the fields is desired, can they be set:
class person{
value(name){
this.name=name.upperCase
}
}
In general, this special logic is to be avoided and it is often a sign of bad style.
Instead it should be moved to class functions, traits or even avoided altogether if there are generalized functions for those fields:
print capitalized name of person
works perfectly fine if we have
name is a string
capitalized string = it.upperCase