Colon Operator

From RemObjects Software

Jump to: navigation, search

This is a Oxygene Language Feature topic
Feel free to add your notes to this topic below.



For 'Joyride', we introduced a new operator type, the Colon Operator, or (:). This new operator acts like the regular member access operator (.) but makes sure that the call does not happen when the value is nil, instead the result of what would have been the call is nil. After having written code for a long time we've noticed that too often we have to write code that simply checks if parts of the expression are assigned before getting the actual value, this new operator makes it possible to check if the expression has a value, if so, call a member on it, else return nil. Added advantage is that the expression is only evaluated once, without the overhead of creating extra local variables.

class method UserInfoList.GetUserSummary(aUsername: string): string;
begin
  result := UserInfo(fUsers[aUserName]):Details:ToString;
  // Will return nil if fUsers[aUsername] returns nil, or if Details is nil
  // else returns the value Details.ToString. fUsers[aUsername] is evaluated
  // exactly once, Details is evaluated zero or one time and ToString also zero
  // or one time.
end;

Colon Operator on Different Types

The Colon Operator can be used on both value and reference types. For value types the member after it will always be invoked, as it cannot be nil. For nullable types, it's only called if the nullable type has a value, when it's not nil, and for reference types it will only be called if the reference is assigned.

Result of the colon operator

The result of the colon operator is always a reference or a nullable type. If the member that is to be called returns a reference or nullable type the result type of the operator is the same as the result of the method. If the result of the member is a value type (such as an Int32), the result will be changed into a nullable of that value type (e.g. a nullable Int32).

class method ConsoleApp.Main;
var
  lInt: Integer := 15;
  lStr: string := nil;
begin
  var s := lInt:ToString;              // returns a String
  var i := lStr:Length;                // returns a nullable<Integer>
end;


See Also

Product: RemObjects Oxygene (formerly known as Chrome)
Current version: 3.0 Previous Versions: 'Joyride' (2.0), 'Floorshow' (1.5), 'Adrenochrome' (1.0)

GlossaryKeywordsLanguage FeaturesPlatform FeaturesSamplesArticlesHow ToIssues

Personal tools