Version 6 (modified by Charles, 12 years ago) |
---|
Expression Tour
This is a "tour" of various kinds of expressions in Cobra. It is intended to help you learn Cobra by quickly highlighting some interesting expressions you can write. It is neither a reference nor an exhaustive list of features. It assumes that the reader has basic familiarity with programming.
Displaying Expression Values
One of the best ways is to display an expression's value is to use the Trace statement which will show the source code of the expression, its value and the location of the trace in the source code (filename, line number, etc.):
trace p.x, p.y
trace: p.x=5; p.y=6; at Foo.cobra:6; in Foo.main
You can, of course, use a Print statement. On a related note, you can validate the value of an expression with an Assert statement.
print 'My name is', name assert x > 0
Arithmetic
Arithmetic has the usual infix operators and parentheses for grouping. Note that division with a single slash (/) gives a fractional value. Use a double slash (//) for "integer" division.
assert 4 / 5 = 0.8 assert 4 // 5 == 0 assert 6 / 5 == 1.2 assert 6 // 5 == 1
Augmented assignment operators can be used to change values:
i += 1 p.x *= 2
Underscores can be put in numbers to separate groups of digits for easier reading:
big = 10_000_000
Bitwise
to-do (& | << >> ~)
Boolean
Boolean expressions include the literals true and false as well as operations such as and, or, not, comparisons and other tests.
obj.isActive = true if obj.isActive, .doSomething
to-do (all, any, don't say ==true or ==false)
Strings
to-do (literals, immutable, common methods, stringbuilder, msdn reference)
Calling Methods
to-do (don't need empty parens, calling on "this", calling base)
Instantiating Types
to-do (use parens, keyword args for properties, combining enums, works on System.Type and dynamic)
Comparing Values
to-do (<>, is & is not vs. == & <>, 0<= i < 10, overriding .equals (and .getHashCode) and .compareTo)
Collections
to-do (list, array, set, dict, explicit creation, indexing, .get, membership(in and not in for lists, arrays, sets, dict.keys, dict.values) )
Slicing
to-do
Type Membership
to-do (inherits, implements, if-inherits, alternative is virtual method)
Casting
to-do (to, to?)
If Expression
to-do
For Expression
to-do
Nil
to-do (nil, to ?, to !, coalesce ? and ?=, ! and !=)
Method References
to-do (ref obj.method)
Expressions in Contracts
to-do (old expr, a implies b, breakout to a method)