Friday, July 15, 2011

LIB2:Conversion to the string

Being a pure object-oriented language ELENA does not support any built-in conversion mechanisms, objects should implement special methods themselves. A standard way to make the object convertible to the string is to implement literal'get method

#class MyLiteral
{
...

#method literal = "My Class".
}

...

#var aLiteral := MyObject literal.

If the object is a number it could implement a numeric protocol. In this case the code will look like this:

#class MyNumber
{
...

#method numeric = 5.
}

...

#var aLiteral := anObject numeric save: std'basic'WideStrConvert.

Note: std'basic'WideStrConvert converts supported numeric values (integer and real numbers) to the literal one.

Let's use more generic code. In this case we have to implement a conversion protocol.

#class MyLiteral
{
...

#method literal = "My Class".

#method request : anObject = anObject literal:($self literal).
}
#class MyNumber
{
...

#method numeric = 5.

#method request  :  anObject = anObject save:($self numeric).
}

...

#var aLiteral := MyObject request:{ 
literal : aLiteral = aLiteral

numeric : aNumber = aNumber save:std'basic'WideStrConvert.
}.

Note: request method is used to define the object supported "type" (either numeric, literal, indexable and so on).

Alternatively we could use existing symbol std'routines'PrintValue:

#var aLiteral := std'routines'PrintValue::MyObject.

In case if our object is a complex one let's consider a last example (see goods sample)

#class Record
{
#field theName.

#field thePrice.

...

#method literal
[
^ ext'text'TextWriter write:"Name:" write:theName write:" Price:" write:thePrice literal.
]
}

...

'program'output << MyRecord.

Note: if PrintValue symbol is used (e.g. in 'program'output) request method may be omitted if the object implements literal'get one.

No comments:

Post a Comment