N9I - 2/12/2010
Written on Fri, 12 Feb 2010 20:11:50 +0000 - Last updated on Fri, 12 Feb 2010 20:29:22 +0000A journal entry in the development of the N9I programming language, dated February 12, 2010
Annotations for creating objects out of other objects
As discussed in N9I - 2/5/2010, the language supports "casting" methods - i.e. methods that "cast" an object into another one. For example,
#@to String
public String toString() ...creates a method that automatically "converts" the object into a string whenever a string is needed:
// assume function someFunc(String str)...
MyObject obj = new MyObject();
someFunc(myObj);In this example, if myObj has a "@to String" method, that method is called on the object such that the someFunc function call is effectively transformed into:
someFunc(myObj.toString());
However, what about the reverse? What if you have a string and need a MyObject? Suppose the class MyObject contains a method:
#@from String
public static MyObject fromString(String str) ...The method is static because it is not attached to any specific MyObject instance, but returns a MyObject. Consider the following:
// assume function someFunc2(MyObject obj)
someFunc2("string representation of a MyObj");
As before, since the function requires a MyObject but gets a string instead, the "@from String" method is called, such that the function call becomes
someFunc2(MyObject.fromString("string representation of a MyObj"));This does not have to be a string, and it does not have to follow the naming convention fromType. It could, for example, be an XML representation
MyObject objectFromXML = @"anObject.xml";
This creates an XML Document object from anObject.xml and then, noticing that the return value is expected to be a MyObject, invokes the "@from Document" static method to create a MyObjectfrom this document. If no such method exists, N9I will use the default XML-to-object function, which might not be appropriate.
It is not required, but heavily encouraged, that the return value from a "@to Foo" method can be passed into a "@from Foo" method to create an identical object.