Is there a default String conversion method in Chapel?

Is there a default method that gets called when trying to pass an object to a string? (For example, toString in Java, or __str__ in Python.) I want to be able to do the following with an array of objects, but some may be nil:

for item in array {
    writeln(item : string);
}

      

+3


source to share


1 answer


First of all, casting the bottom to a string isn't necessarily a problem:

class C {
  var x:int;
}

var array = [ new C(1), nil:C, new C(2) ];

for item in array {
  writeln( item : string ); 
}

      

outputs

{x = 1}
nil
{x = 2}

      

Second, if you want to customize the output of your C class, you must write a writeThis method (or a readWriteThis method). See the readThis (), writeThis (), and readWriteThis () methods . The writeThis method will be called for both string translation and normal I / O. For example:



class C {
  var x:int;
  proc writeThis(writer) {
    writer.writef("{%010i}", x);
  }
}

var array = [ new C(1), nil:C, new C(2) ];

for item in array {
  writeln( "writing item : string  ", item : string ); 
  writeln( "writing item           ", item);
}

      

outputs

writing item : string  {0000000001}
writing item           {0000000001}
writing item : string  nil
writing item           nil
writing item : string  {0000000002}
writing item           {0000000002}

      

I can tell you why it works in a way that it might do in the future and the limitations of the current strategy ... but the mailing list would be the best place for that discussion if you enjoy having it.

+3


source







All Articles